Determine via C# whether a string is a valid file path
I would like to know how to determine whether string is valid file path.
The file path may or may not exist.
Solution 1:
You can use the FileInfo constructor. It will throw a ArgumentException if "The file name is empty, contains only white spaces, or contains invalid characters." It can also throw SecurityException or UnauthorizedAccessException, which I think you can ignore if you're only concerned about format.
Another option is to check against Path.GetInvalidPathChars directly. E.g.:
boolean possiblePath = pathString.IndexOfAny(Path.GetInvalidPathChars()) == -1;
Solution 2:
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
Solution 3:
Here are some things you might use:
- to check if the drive is correct (for example on one computer the drive X:\ exists, but not on yours): use
Path.IsPathRooted
to see if it's not a relative path and then use the drives fromEnvironment.GetLogicalDrives()
to see if your path contains one of the valid drives. - To check for valid characters, you have two methods:
Path.GetInvalidFileNameChars()
andPath.GetInvalidPathChars()
which don't overlap completely. You can also usePath.GetDirectoryName(path)
andPath.GetFileName(fileName)
with your input name, which will throw an exception if
The path parameter contains invalid characters, is empty, or contains only white spaces.