views:

8173

answers:

11

Is there a method in the System.IO namespace that checks the validity of a filename?

Example: 'C:\foo\bar' would validate ':"~-*' would not

a little trickier: 'X:\foo\bar' would validate is there is an X: drive on the system, but wouldn't otherwise.

I suppose I could write such a method myself, but I'm more interested in a built-in one.

+5  A: 

You can get a list of invalid characters from Path.GetInvalidPathChars and GetInvalidFileNameChars as discussed in this question.

As Micah points out, there is Directory.GetLogicalDrives to get a list of valid drives.

Eugene Katz
+7  A: 

Just do

bool bOk = false;
try
{
  new System.IO.FileInfo(fileName);
  bOk = true;
}
catch (ArgumentException)
{
}
catch (System.IO.PathTooLongException)
{
}
catch (NotSupportedException)
{
}
if (!bOk)
{
  ...
}
else
{
  ...
}

For creating a FileInfo instance the file does not need to exist.

Edit: You can afterward do FileInfo.Exists to check if the file exists or not.

Edit2: Added better exception handling according to MSDN documentation for FileInfo constructor.

rstevens
Be careful with FileInfo. Any string, even if it's just a single letter is a valid argument in the constructor, but simply trying new FileInfo(pathTheuserEntered) will cause FileInfo to assume the file is relative to the current working directory, which might not be what you want.
Echilon
A: 

Use the static GetInvalidFileNameChars method on the Path class in the System.IO namespace to determine what characters are illegal in a file name.

To do so in a path, call the static GetInvalidPathChars method on the same class.

To determine if the root of a path is valid, you would call the static GetPathRoot method on the Path class to get the root, then use the Directory class to determine if it is valid. Then you can validate the rest of the path normally.

casperOne
A: 

There is such a method somewhere in the framework, and I'm sure someone will post it here. However, what I remember also is that this method is imperfect (i.e., buggy), and has issues with things like localization.

Dmitri Nesteruk
+2  A: 

Even if the filename is valid, you may still want to touch it to be sure the user has permission to write.

If you won't be thrashing the disk with hundreds of files in a short period of time, I think creating an empty file is a reasonable approach.

If you really want something lighter, like just checking for invalid chars, then compare your filename against Path.GetInvalidFileNameChars().

Michael Haren
A: 

Probably the bast way is to build a custom method mixing a combination of regex and small look up on your file system (to see the drives, for example)

tanathos
A: 

I don't know of anything out of the box that can just validate all of that for you, however the Path class in .NET can help you out tremendously.

For starters, it has:

 char[] invalidChars = Path.GetInvalidFileNameChars(); //returns invalid charachters

Or:

Path.GetPathRoot(string); // will return the root.
BFree
+1  A: 

Several of the System.IO.Path methods will throw exceptions if the path or filename is invalid:

  • Path.IsPathRooted()
  • Path.GetFileName()

http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx

shackett
+3  A: 

There are several methods you could use that exist in the System.IO namespace:

Directory.GetLogicalDrives() // Returns an array of strings like "c:\"
Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name
Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path.

As suggested you could then do this:

bool IsValidFilename(string testName)
{
        Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");
        if (containsABadCharacter.IsMatch(testName) { return false; };

        //Check for drive
        if(Director.GetLogicalDrives.Contains(Path.GetPathRoot(textName)))


        // other checks for UNC, drive-path format, etc

        return true;
}
Micah
Not going to vote down, but you really should give credit when using sample code from other people, especially when it's not really correct.http://stackoverflow.com/questions/62771/how-check-if-given-string-is-legal-allowed-file-name-under-windows#62855
Eugene Katz
A: 

This will get you the drives on the machine:

System.IO.DriveInfo.GetDrives()

These two methods will get you the bad characters to check:

System.IO.Path.GetInvalidFileNameChars();
System.IO.Path.GetInvalidPathChars();
Austin Salonen
A: 

I've had luck using regular expressions as others have shown.

One thing to keep in mind is that Windows at least prohibits some filenames that otherwise containlegal characters. A few come to mind: com, nul, prn.

I don't have it with me now, but I have a regex that takes these filename into consideration. If you want I can post it, otherwise I'm sure you can find it the same way I did: Google.

-Jay

Jay Riggs