132

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

For example, C:\foo\bar would validate and :"~-* would not

Or 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.

1
  • Does the "not that it exits" require validating the folders exist or no? What are the boundaries of the check? That the drive exists and that the characters are all valid? Jan 7, 2009 at 21:14

14 Answers 14

99

Just do;

System.IO.FileInfo fi = null;
try {
  fi = new System.IO.FileInfo(fileName);
}
catch (ArgumentException) { }
catch (System.IO.PathTooLongException) { }
catch (NotSupportedException) { }
if (ReferenceEquals(fi, null)) {
  // file name is not valid
} else {
  // file name is valid... May check for existence by calling fi.Exists.
}

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

9
  • 17
    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
    Jan 2, 2010 at 12:14
  • 1
    I enhanced this solution using bOk = System.IO.Path.IsPathRooted(fileName); instead of bOk = true;
    – jing
    Sep 24, 2013 at 7:12
  • 5
    This doesn't catch a file name containing '/' which isn't valid.
    – Marc
    Oct 15, 2013 at 6:53
  • 1
    You can add a check for your filename containing any of the characters in the array returned by char[] badChars = Path.GetInvalidFileNameChars(); Feb 12, 2015 at 18:27
  • 2
    @SimonElms That's because those are valid filename characters on most Linux file systems! It seems we have to find another solution for .NET >=5 which also allows to specify the file system...
    – mmmmmmmm
    Mar 14, 2023 at 4:30
36

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

As noted by jberger, there some other characters which are not included in the response from this method. For much more details of the windows platform, take a look at Naming Files, Paths and Namespaces on MSDN.

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

4
  • 4
    "The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names." Remarks Jun 28, 2011 at 21:22
  • 1
    Let me reiterate on that. The characters alone aren't enough to know that it's valid. For example, : is valid zero or one times, but it's NOT ALWAYS the second character in the string if it exists!
    – Robert P
    Mar 14, 2013 at 17:17
  • 2
    This is not correct. Certain names are also prohibited, not just certain characters. May 19, 2017 at 9:45
  • "DD:\\\\\AAA.....AAAA". Not valid, but for your code, it is. Jul 2, 2020 at 20:06
21

You could make use the System.Uri class. The Uri class isn't just useful for web URLs, it also handles file system paths as well. Use the Uri.TryCreate method to find if the path is rooted then use the IsLoopback property to determine if the Uri references the local machine.

Here is a simple method which determines if a string is a valid, local, and rooted file path.

public bool IsPathValidRootedLocal(String pathString) {
    Uri pathUri;
    Boolean isValidUri = Uri.TryCreate(pathString, UriKind.Absolute, out pathUri);
    return isValidUri && pathUri != null && pathUri.IsLoopback;
}

I am confident this will work.

4
  • 1
    You should also check if Uri.Schema is a file.
    – drowa
    Feb 9, 2018 at 20:18
  • 2
    Also, things like file:///a would be accepted as a valid path by your method.
    – drowa
    Feb 9, 2018 at 20:24
  • Also doesn't work if you have question mark at the end. C:\\foo\\bar??
    – Lion King
    Mar 8, 2018 at 9:33
  • 5
    Returns true for @"C:\Dir\Invalid*?*Characters.txt", even though both the * and ? characters are invalid in a file name.
    – Simon Elms
    Mar 12, 2022 at 9:26
9

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) {
    string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]";
    Regex containsABadCharacter = new Regex(regexString);
    if (containsABadCharacter.IsMatch(testName)) {
        return false;
    }

    // Check for drive
    string pathRoot = Path.GetPathRoot(testName);
    if (Directory.GetLogicalDrives().Contains(pathRoot)) {
        // etc
    }

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

    return true;
}
3
  • 20
    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. stackoverflow.com/questions/62771/… Jan 7, 2009 at 21:30
  • 4
    "regexString" should look more like: string regexStringPath = "[" + Regex.Escape(new string (System.IO.Path.GetInvalidPathChars())) + "]";
    – panako
    Feb 5, 2014 at 10:59
  • What is about @"C:\\Windows" (indeed with double-backslash)? Explorer says it is not a valid path, but you don't check this. Aug 25, 2017 at 13:31
8

Thought I would post a solution I cobbled together from bits of answers I found after searching for a robust solution to the same problem. Hopefully it helps someone else.

using System;
using System.IO;
//..

public static bool ValidateFilePath(string path, bool RequireDirectory, bool IncludeFileName, bool RequireFileName = false)
{
    if (string.IsNullOrEmpty(path)) { return false; }
    string root = null;
    string directory = null;
    string filename = null;
    try
    {
        // throw ArgumentException - The path parameter contains invalid characters, is empty, or contains only white spaces.
        root = Path.GetPathRoot(path);

        // throw ArgumentException - path contains one or more of the invalid characters defined in GetInvalidPathChars.
        // -or- String.Empty was passed to path.
        directory = Path.GetDirectoryName(path);

        // path contains one or more of the invalid characters defined in GetInvalidPathChars
        if (IncludeFileName) { filename = Path.GetFileName(path); }
    }
    catch (ArgumentException)
    {
        return false;
    }

    // null if path is null, or an empty string if path does not contain root directory information
    if (String.IsNullOrEmpty(root)) { return false; }

    // null if path denotes a root directory or is null. Returns String.Empty if path does not contain directory information
    if (String.IsNullOrEmpty(directory)) { return false; }

    if (RequireFileName)
    {
        // if the last character of path is a directory or volume separator character, this method returns String.Empty
        if (String.IsNullOrEmpty(filename)) { return false; }

        // check for illegal chars in filename
        if (filename.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { return false; }
    }
    return true;
}
1
  • 1
    FYI, in case anyone tries to use this solution in a newer version of .NET...it will no longer work as expected. An ArgumentException is not raised given invalid characters. Not sure exactly when this change was introduced, but I can confirm it was before .NET 6. Found documentation describing it for .NET Core 2.1 here: github.com/dotnet/dotnet-api-docs/issues/1685
    – miesch1
    Jan 15 at 19:03
6

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().

1
  • This is the simplest, best solution. But make sure it does not exist before using File.Create(), in case it already exists.
    – user1908746
    May 28, 2022 at 8:31
2

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

3
  • This does not appear to be true, at least in Mono (e.g. in Unity). I'm using a bogus path of "Bogus\\Invalid!/No:Such?File!*@#!", and IsPathRooted returns true, GetFileName returns the part after the slash, and FileInfo completely fails to throw an exception. (However calling GetDirectories on the directory does throw an exception, so maybe that's the answer in my case.)
    – Joe Strout
    Aug 24, 2016 at 15:15
  • That does not work. Path.GetFileName("*xxx?") will return "*xxx?" with no exception. Also don't forget about reserved file names that will be incorrect for new files. In Windows those are "prn", "con" etc.
    – epox
    Apr 21, 2017 at 8:03
  • This answer is wrong.
    – rory.ap
    Aug 25, 2017 at 18:01
2

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

2

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.

2
  • 1
    "The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names." Remarks Jun 28, 2011 at 21:23
  • Expanding upon what RobertP said above... Using GetInvalidPathChars in and by itself is not an exactly correct way to test the validity of a string that represents a path. This method returns the 'control' characters and " > < | Meaning that this string (minus the enclosing double quotes) is valid "C:\Folder1\Folder*2\Fol:der3". Now open up Windows Explorer or a command console and try to create that folder structure and let me know what happens... You need to break the path down into its components and test for a valid volume designator and test each directory component as a valid filename
    – PMBottas
    May 25, 2013 at 1:41
2

Try out this method which would try to cover for all the possible Exceptions scenarios. It would work for almost all the Windows related Paths.

/// <summary>
/// Validate the Path. If path is relative append the path to the project directory by default.
/// </summary>
/// <param name="path">Path to validate</param>
/// <param name="RelativePath">Relative path</param>
/// <param name="Extension">If want to check for File Path</param>
/// <returns></returns>
private static bool ValidateDllPath(ref string path, string RelativePath = "", string Extension = "") {
    // Check if it contains any Invalid Characters.
    if (path.IndexOfAny(Path.GetInvalidPathChars()) == -1) {
        try {
            // If path is relative take %IGXLROOT% as the base directory
            if (!Path.IsPathRooted(path)) {
                if (string.IsNullOrEmpty(RelativePath)) {
                    // Exceptions handled by Path.GetFullPath
                    // ArgumentException path is a zero-length string, contains only white space, or contains one or more of the invalid characters defined in GetInvalidPathChars. -or- The system could not retrieve the absolute path.
                    // 
                    // SecurityException The caller does not have the required permissions.
                    // 
                    // ArgumentNullException path is null.
                    // 
                    // NotSupportedException path contains a colon (":") that is not part of a volume identifier (for example, "c:\"). 
                    // PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

                    // RelativePath is not passed so we would take the project path 
                    path = Path.GetFullPath(RelativePath);

                } else {
                    // Make sure the path is relative to the RelativePath and not our project directory
                    path = Path.Combine(RelativePath, path);
                }
            }

            // Exceptions from FileInfo Constructor:
            //   System.ArgumentNullException:
            //     fileName is null.
            //
            //   System.Security.SecurityException:
            //     The caller does not have the required permission.
            //
            //   System.ArgumentException:
            //     The file name is empty, contains only white spaces, or contains invalid characters.
            //
            //   System.IO.PathTooLongException:
            //     The specified path, file name, or both exceed the system-defined maximum
            //     length. For example, on Windows-based platforms, paths must be less than
            //     248 characters, and file names must be less than 260 characters.
            //
            //   System.NotSupportedException:
            //     fileName contains a colon (:) in the middle of the string.
            FileInfo fileInfo = new FileInfo(path);

            // Exceptions using FileInfo.Length:
            //   System.IO.IOException:
            //     System.IO.FileSystemInfo.Refresh() cannot update the state of the file or
            //     directory.
            //
            //   System.IO.FileNotFoundException:
            //     The file does not exist.-or- The Length property is called for a directory.
            bool throwEx = fileInfo.Length == -1;

            // Exceptions using FileInfo.IsReadOnly:
            //   System.UnauthorizedAccessException:
            //     Access to fileName is denied.
            //     The file described by the current System.IO.FileInfo object is read-only.-or-
            //     This operation is not supported on the current platform.-or- The caller does
            //     not have the required permission.
            throwEx = fileInfo.IsReadOnly;

            if (!string.IsNullOrEmpty(Extension)) {
                // Validate the Extension of the file.
                if (Path.GetExtension(path).Equals(Extension, StringComparison.InvariantCultureIgnoreCase)) {
                    // Trim the Library Path
                    path = path.Trim();
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;

            }
        } catch (ArgumentNullException) {
            //   System.ArgumentNullException:
            //     fileName is null.
        } catch (System.Security.SecurityException) {
            //   System.Security.SecurityException:
            //     The caller does not have the required permission.
        } catch (ArgumentException) {
            //   System.ArgumentException:
            //     The file name is empty, contains only white spaces, or contains invalid characters.
        } catch (UnauthorizedAccessException) {
            //   System.UnauthorizedAccessException:
            //     Access to fileName is denied.
        } catch (PathTooLongException) {
            //   System.IO.PathTooLongException:
            //     The specified path, file name, or both exceed the system-defined maximum
            //     length. For example, on Windows-based platforms, paths must be less than
            //     248 characters, and file names must be less than 260 characters.
        } catch (NotSupportedException) {
            //   System.NotSupportedException:
            //     fileName contains a colon (:) in the middle of the string.
        } catch (FileNotFoundException) {
            // System.FileNotFoundException
            //  The exception that is thrown when an attempt to access a file that does not
            //  exist on disk fails.
        } catch (IOException) {
            //   System.IO.IOException:
            //     An I/O error occurred while opening the file.
        } catch (Exception) {
            // Unknown Exception. Might be due to wrong case or nulll checks.
        }
    } else {
        // Path contains invalid characters
    }
    return false;
}
1

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.
0

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)

0

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();
0

Think it's too late to answer but... :) in case of path with volume name you could write something like this:

using System;
using System.Linq;
using System.IO;

// ...

var drives = Environment.GetLogicalDrives();
var invalidChars = Regex.Replace(new string(Path.GetInvalidFileNameChars()), "[\\\\/]", "");
var drive = drives.FirstOrDefault(d => filePath.StartsWith(d));
if (drive != null) {
    var fileDirPath = filePath.Substring(drive.Length);
    if (0 < fileDirPath.Length) {
        if (fileDirPath.IndexOfAny(invalidChars.ToCharArray()) == -1) {
            if (Path.Combine(drive, fileDirPath) != drive) {
                // path correct and we can proceed
            }
        }
    }
}