views:

209

answers:

3

In c# how can I check in the file name has the "pound sign" and "apostrophe sign" This is waht I tried so far but doesn't work. I need to send an error if the # or ' are in the filename

return filename.Contains("#\'");

+2  A: 

Try the following

bool HasBadCharacters(string fileName) {
  return fileName.IndexOf('\'') >= 0 || fileName.IndexOf('#') >= 0;
}

This code will check the entire file name passed in. So if you passed in a full path it would check the file name and all of the directory names in the path to the file. If you just want to check the file name, then make sure to use Path.GetFileName() on the string before passing it into HasBadCharacters.

JaredPar
+3  A: 

Try something like this:

Regex.IsMatch(fileName, @"[#']");
Andrew Hare
+8  A: 

You can use IndexOfAny:

if (filename.IndexOfAny(new char[] {'#', '\''}) > -1)
{
    // filename contains # or '
}
fretje