In C# Check That Filename Is *Possibly* Valid (Not That It Exists)

How do I check if a given string is a legal/valid file name under Windows?

You can get a list of invalid characters from Path.GetInvalidPathChars and GetInvalidFileNameChars.

UPD: See Steve Cooper's suggestion on how to use these in a regular expression.

UPD2: Note that according to the Remarks section in MSDN "The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names." The answer provided by sixlettervaliables goes into more details.

Easiest way to check if an arbitrary String is a valid filename

Check whether filename.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 and !File.Exists(Path.Combine(someFolder, filename))

Determine via C# whether a string is a valid file path

A 100% accurate checking of a path's string format is quite difficult, since it will depend on the filesystem on which it is used (and network protocols if its not on the same computer).

Even within windows or even NTFS its not simple since it still depends on the API .NET is using in the background to communicate with the kernel.

And since most filesystems today support unicode, one might also need to check for all the rules for correcly encoded unicode, normalization, etc etc.

What I'd do is to make some basic checks only, and then handle exceptions properly once the path is used. For possible rules see:

  • Wikipedia - Filename for an overview of the rules used by different file systems
  • Naming Files, Paths, and Namespaces for windows specific rules

Is there a way to verify a valid path / file name?

To check whether a file exists at a specified path, use System.IO.File.Exists(string path):

if (File.Exists(pathFileName))

To check whether a path or file name is valid (I.E. contains no illegal characters) use System.IO.Path.GetInvalidPathChars() or System.IO.Path.GetInvalidFileNameChars():

if (Path.GetInvalidFileNameChars().Any(c => pathFileName.Contains(c)))

Related Topics

Leave a reply