Problem Checking the End of a String - c#

This seems to be a very odd problem that I cannot figure out for the life of me. I have a path (string) that looks like this:
D:\development\php\bchat\chat\index.php
I need to check if the file in question is a PHP file. I figure the most logical way is to take a substring starting from the . to the end of the string and see if it == .php
So i tried:
bool isphp = (path.Substring(path.LastIndexOf('.')) == ".php") ? true : false;
This always returned false. I thought maybe there was a trailing space at the end screwing me up so i put a TrimEnd() on path before it. But that didn't change anything. So i tried this:
bool isphp = (path.EndsWith(".php") == true) ? true : false;
This also always returns false.
EDIT
I have now also tried this:
bool isphp = (Path.GetExtension(path) == ".php");
But this also returns false.

Use the Path-class. It has a GetExtension() method:
var path = #"D:\development\php\bchat\chat\index.php";
if( Path.GetExtension( path.ToUpperInvariant() ) == ".PHP" )
{}
EDIT: Added check for upper/lower cases

The following code works fine on my machine:
public static void Main()
{
string path = #"D:\development\php\bchat\chat\index.php";
bool isPhp = path.EndsWith(".php");
Console.WriteLine(isPhp);
}
So I would guess there is something else about your string that is causing it not to work. Maybe it is a case thing in which case add StringComparison.InvariantCultureIgnoreCase to your EndsWith call like this.
public static void Main()
{
string path = #"D:\development\php\bchat\chat\index.pHp";
bool isPhp = path.EndsWith(".php", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(isPhp);
}
If that doesn't work put a break point on the comparison line and then type this into the Immediate window:
path[path.Length-1]
You should get this as a result:
112 'p'
If you don't you can tell that your path does not end with a standard p character.

Just a sample for the posted solution:
bool isphp = Path.GetExtension(path)
.Equals(".php", StringComparison.InvariantCultureIgnoreCase);

If it is an existing file you can get the FileInfo object for it and check the extension that way:
FileInfo fi = new FileInfo(#"D:\development\php\bchat\chat\index.php");
if (fi.Exists && fi.Extension == ".php")
{
//Do something
}
Or I suppose you could be a sheep, follow the crowd and use the far better Path.GetExtension method that everyone else has suggested. But ask yourself this question first - do you want to do it the cleanest, fastest and best way, or do you want to assert your individuality and join me down the path of most resistance?

Use Path.GetExtension and compare with the file type you're looking for.

What about Path.GetExtension method?

Make sure that there is no difference in upper/lowercase. You are only testing for lowercase "php".
string ext = Path.GetExtension(path);
bool isPhp = (ext.Equals(".php", StringComparison.InvariantCultureIgnoreCase));

UPDATE:
Check what path.Substring(path.LastIndexOf('.') actually returns - that might point you in the right direction.

private static bool IsPhp(string fileName)
{
return string.Compare(Path.GetExtension(fileName), ".php",
StringComparison.OrdinalIgnoreCase) == 0;
}

I suspect there's something "odd" in your string. I suggest you dump your string out in detail, like this:
foreach (char c in path)
{
Console.WriteLine("'{0}' U+{1:x4}", c, (int) c);
}
That way you'll see any unexpected characters, e.g. unicode char 0s between "real" characters.

Related

Is there a function to check whether a path is included in the path?

I would like to check the path.
For example, I want a method that has functionality below.
Two path string is "C:\Document\test", "C:Document\test2".
And If "C:\Document\test" is compared with "C:Document\test2" then the result is expected false because "C:\Document\test" is not included in "C:Document\test2".
Another example is
Two path string is "C:\Document\test", "C:Document\test\test2".
If "C:\Document\test" is compared with "C:Document\test\test2" then the resulut is expected true because "C:\Document\test" is included in "C:Document\test\test2".
Is there a method that has functionality the above in C#?
Thanks for reading.
You could use string comparison for the purpose. For example,
public static bool ComparePath(string path1,string path2)
{
return NormalizePath(path2).Contains(NormalizePath(path1));
}
public static string NormalizePath(string path)
{
if(path.Trim().Last().Equals(Path.DirectorySeparatorChar))
return path.Trim().ToLower();
return $"{path.Trim()}{Path.DirectorySeparatorChar}".ToLower();
}
You need to include the DirectorySeparatorChar to mark end of path.
Example,
ComparePath(#"C:\Document\test",#"C:\Document\test\2"); // True
ComparePath(#"C:\Document\test",#"C:\Document\test2"); // False
I think the PathUtil.IsDescendant(String, String) Method is exactly what you Need. You find the documentation here.
var res = PathUtil.IsDescendant("C:\\Test\\Test1\\", "C:\\Test\\Test1\\Test2.txt");
res = PathUtil.IsDescendant("C:\\Test\\Test", "C:\\Test\\Test2");
The first will return trueand the second will return false

Regex for string without spacial characters or spaces [duplicate]

How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$

C# string comparision error

I am trying to check if value exists in a string array. The below one works but when I tried the next code block, it failed.
bool exixts;
string toCheck= "jupiter";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck))
{
exists = true;
}
How can I check for trim and case sensitivity?
I tried this
bool exixts;
string toCheck= "jupiter ";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
{
exists = true;
}
The IEnumerable<string>.Contains(value, comparer) expects a compare class instance, not an enum value.
The library does have some ready made comparers available though:
//if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
if (printer.Contains(toCheck.Trim(), StringComparer.OrdinalIgnoreCase))
Or you can do like this,
bool exists = printer.Any(x=> x == toCheck.Trim());
Hope helps,

Check if string contains a number c#

I know that there is lots of questions like this out there.
But I really couldn't find anything that solved my problem.
I want to check if the string contains the specific input number. See the following example:
public Boolean checkString()
{
string input = "2.5.8.12.30";
string intToFind = "3";
if (input.contains(intToFind))
{
return true;
}
else
{
return false;
}
}
This returns true but I want it to return false since the intToFind string is 3 and not 30. So it is the contains() that is the problem.
How do I make it search for 3 only?
You could use String.Split + Contains:
bool contains3 = input.Split('.').Contains("3");
bool anyThree = input.Split('.').Any(str => str == "3");
You may split your input using String.Split('.') into an array. Now use Array.contains to check if the element is within the array
bool contained = input.Split('.').Contains("3");
string[] words = input.Split('.');
if (words.contains("3")){do something...}
You could also use Regex which might be a little overkill.
string str = "2.5.8.12.30";
string strToFind = "3";
bool contains = Regex.Match(str, string.Format(#"\W{0}\W",strToFind)).Success;

If else minifier

I have many lines of code like this.. this is just a 1 thing i am trying right now.
if (RI2.Text.Contains("SOS") || RI2.Text.Contains("WAR"))
{
Response.Redirect("http://mydomain.com/rabat");
}
if (RI2.Text.Contains("sos") || RI2.Text.Contains("war"))
{
Response.Redirect("http://mydomain.com/rabat");
}
How do i minify this code. i mean, its very ugly and there many lines of code similar to this.
is there any better way of doing this which i dont know.
please help. appreciate your time and help.
Try this regular expression.
Ignores case in comparison (SOS and sos matched)
Does not mutate the strings as you don't call ToLower()
Only 2 lines of code
You can optionally precompile the expression if the expression (SOS|WAR) is a constant for more performance.
if (Regex.IsMatch(RI2.Text, "SOS|WAR", RegexOptions.IgnoreCase))
Response.Redirect("http://mydomain.com/rabat");
Not sure I fully understand your requirements, but here you go:
if(RI2.Text.ToLower().Contains("sos") || RI2.Text.ToLower().Contains("war")) {
Response.Redirect("http://mydomain.com/rabat");
}
you can do one call, like
//this will accept "SOS" and "sos"
if(RI2.Text.ToLower().Contains("sos") ||
RI2.Text.ToLower().Contains("war"))
{
....
}
You could convert the string to lowercase removing one if statement and then use a linq any statement.
var search=new[] {"sos","war"};
if (search.Any(x=>RI2.Text.ToLower().Contains(x))) {
Response.Redirect("http://mydomain.com/rabat");
}
Or even make collection of matches to target urls.
var search = new Dictionary<string,string>{
{"sos","http://mydomain.com/rabat"},
{"war","http://mydomain.com/rabat"},
};
The use linq
var url=search.Keys.Where(x=>RI2.Text.ToLower().Contains(x)).Select(x=>search[x]).FirstOrDefault();
if (url!=null) {
Response.Redirect(url);
}
You could create a extention to string as follows
public static bool Contains(this string value, string[] values)
{
foreach (string comparar in values)
{
if (value.ToUpper().Contains(comparar.ToUpper())) return true;
}
return false;
}
Instead of converting the string to lower or upper case use string.IndexOf with ignore case
if (RI2.Text.IndexOf("sos",StringComparison.InvariantCultureIgnoreCase) >= 0 ||
RI2.Text.IndexOf("war",StringComparison.InvariantCultureIgnoreCase) >= 0 )
{
Response.Redirect("http://mydomain.com/rabat");
}
if(string.Equals("war", RI2.Text, StringComparison.InvariantCultureIgnoreCase) ||
string.Equals("sos", RI2.Text, StringComparison.InvariantCultureIgnoreCase))
Response.Redirect("http://mydomain.com/rabat");
Create a list of string pairs, with one being the search string in upper case and the other being the redirect location.
Iterate through the list checking each search string against the upper-case text. If you find a match redirect to the location specified in the pair.
Use Regex:
var pattern = "(sos|war)";
if(Regex.IsMatch(RI2.Text.ToLower(), pattern))
Response.Redirect("http://mydomain.com/rabat");
Given that both the Url for Response.Redirect are same
string lowerRI2 = RI2.Text.ToLower();
if (lowerRI2.Contains("sos") || lowerRI2.Contains("war"))
Response.Redirect("http://mydomain.com/rabat");

Categories