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))
{
...
}
else
{
...
}
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
Differencebetween a Property and a Variable
Why Is There No Char.Empty Like String.Empty
Declaration Suffix for Decimal Type
How to Read Data from a Zip File Without Having to Unzip the Entire File
C# - Detect Time of Last User Interaction with the Os
Appsettings Get Value from .Config File
Failed to Serialize the Response in Web API
What Is Quicker, Switch on String or Elseif on Type
How to "Flatten" or "Index" 3D-Array in 1D Array
Easiest Way to Read from a Url into a String in .Net
What Is an MVChtmlstring and When Should I Use It
Web API 2: How to Return JSON with Camelcased Property Names, on Objects and Their Sub-Objects