Regular expressions in C# for file name validation

c#, regex

Solution

As answered already, GetInvalidFileNameChars should do it for you, and you don't even need the overhead of regular expressions:

if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
{
  MessageBox.Show("The filename is invalid");
  return;
}

Problem

What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have `\/:*?"<>|` characters). I'd like to use it like the following: ``` // Return true if string is invalid. if (Regex.IsMatch(szFileName, "<your regex string>")) { // Tell user to reformat their filename. } ```

Original source