Question

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("#\'");

Was it helpful?

Solution

You can use IndexOfAny:

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

OTHER TIPS

Try something like this:

Regex.IsMatch(fileName, @"[#']");

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top