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

C#WindowsFileFilesystems

C# Problem Overview


I want to include a batch file rename functionality in my application. A user can type a destination filename pattern and (after replacing some wildcards in the pattern) I need to check if it's going to be a legal filename under Windows. I've tried to use regular expression like [a-zA-Z0-9_]+ but it doesn't include many national-specific characters from various languages (e.g. umlauts and so on). What is the best way to do such a check?

C# Solutions


Solution 1 - C#

From [MSDN's "Naming a File or Directory,"][1] here are the general conventions for what a legal file name is under Windows:

You may use any character in the current code page (Unicode/ANSI above 127), except:

  • < > : " / \ | ? *
  • Characters whose integer representations are 0-31 (less than ASCII space)
  • Any other character that the target file system does not allow (say, trailing periods or spaces)
  • Any of the DOS names: CON, PRN, AUX, NUL, COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9 (and avoid AUX.txt, etc)
  • The file name is all periods

Some optional things to check:

  • File paths (including the file name) may not have more than 260 characters (that don't use the \?\ prefix)
  • Unicode file paths (including the file name) with more than 32,000 characters when using \?\ (note that prefix may expand directory components and cause it to overflow the 32,000 limit)

[1]: http://msdn.microsoft.com/en-us/library/aa365247.aspx "Naming a File or Directory"

Solution 2 - C#

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.

Solution 3 - C#

For .Net Frameworks prior to 3.5 this should work:

Regular expression matching should get you some of the way. Here's a snippet using the System.IO.Path.InvalidPathChars constant;

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

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

	return true;
}

For .Net Frameworks after 3.0 this should work:

http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars(v=vs.90).aspx

Regular expression matching should get you some of the way. Here's a snippet using the System.IO.Path.GetInvalidPathChars() constant;

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

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

	return true;
}

Once you know that, you should also check for different formats, eg c:\my\drive and \\server\share\dir\file.ext

Solution 4 - C#

Try to use it, and trap for the error. The allowed set may change across file systems, or across different versions of Windows. In other words, if you want know if Windows likes the name, hand it the name and let it tell you.

Solution 5 - C#

This is what I use:

    public static bool IsValidFileName(this string expression, bool platformIndependent)
    {
        string sPattern = @"^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+$";
        if (platformIndependent)
        {
           sPattern = @"^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?))\\)*[^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?$";
        }
        return (Regex.IsMatch(expression, sPattern, RegexOptions.CultureInvariant));
    }

The first pattern creates a regular expression containing the invalid/illegal file names and characters for Windows platforms only. The second one does the same but ensures that the name is legal for any platform.

Solution 6 - C#

This class cleans filenames and paths; use it like

var myCleanPath = PathSanitizer.SanitizeFilename(myBadPath, ' ');

Here's the code;

/// <summary>
/// Cleans paths of invalid characters.
/// </summary>
public static class PathSanitizer
{
    /// <summary>
    /// The set of invalid filename characters, kept sorted for fast binary search
    /// </summary>
    private readonly static char[] invalidFilenameChars;
    /// <summary>
    /// The set of invalid path characters, kept sorted for fast binary search
    /// </summary>
    private readonly static char[] invalidPathChars;

    static PathSanitizer()
    {
        // set up the two arrays -- sorted once for speed.
        invalidFilenameChars = System.IO.Path.GetInvalidFileNameChars();
        invalidPathChars = System.IO.Path.GetInvalidPathChars();
        Array.Sort(invalidFilenameChars);
        Array.Sort(invalidPathChars);

    }

    /// <summary>
    /// Cleans a filename of invalid characters
    /// </summary>
    /// <param name="input">the string to clean</param>
    /// <param name="errorChar">the character which replaces bad characters</param>
    /// <returns></returns>
    public static string SanitizeFilename(string input, char errorChar)
    {
        return Sanitize(input, invalidFilenameChars, errorChar);
    }

    /// <summary>
    /// Cleans a path of invalid characters
    /// </summary>
    /// <param name="input">the string to clean</param>
    /// <param name="errorChar">the character which replaces bad characters</param>
    /// <returns></returns>
    public static string SanitizePath(string input, char errorChar)
    {
        return Sanitize(input, invalidPathChars, errorChar);
    }

    /// <summary>
    /// Cleans a string of invalid characters.
    /// </summary>
    /// <param name="input"></param>
    /// <param name="invalidChars"></param>
    /// <param name="errorChar"></param>
    /// <returns></returns>
    private static string Sanitize(string input, char[] invalidChars, char errorChar)
    {
        // null always sanitizes to null
        if (input == null) { return null; }
        StringBuilder result = new StringBuilder();
        foreach (var characterToTest in input)
        {
            // we binary search for the character in the invalid set. This should be lightning fast.
            if (Array.BinarySearch(invalidChars, characterToTest) >= 0)
            {
                // we found the character in the array of 
                result.Append(errorChar);
            }
            else
            {
                // the character was not found in invalid, so it is valid.
                result.Append(characterToTest);
            }
        }

        // we're done.
        return result.ToString();
    }

}

Solution 7 - C#

One corner case to keep in mind, which surprised me when I first found out about it: Windows allows leading space characters in file names! For example, the following are all legal, and distinct, file names on Windows (minus the quotes):

"file.txt"
" file.txt"
"  file.txt"

One takeaway from this: Use caution when writing code that trims leading/trailing whitespace from a filename string.

Solution 8 - C#

Simplifying the Eugene Katz's answer:

bool IsFileNameCorrect(string fileName){
    return !fileName.Any(f=>Path.GetInvalidFileNameChars().Contains(f))
}

Or

bool IsFileNameCorrect(string fileName){
    return fileName.All(f=>!Path.GetInvalidFileNameChars().Contains(f))
}

Solution 9 - C#

Microsoft Windows: Windows kernel forbids the use of characters in range 1-31 (i.e., 0x01-0x1F) and characters " * : < > ? \ |. Although NTFS allows each path component (directory or filename) to be 255 characters long and paths up to about 32767 characters long, the Windows kernel only supports paths up to 259 characters long. Additionally, Windows forbids the use of the MS-DOS device names AUX, CLOCK$, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, CON, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9, NUL and PRN, as well as these names with any extension (for example, AUX.txt), except when using Long UNC paths (ex. \.\C:\nul.txt or \?\D:\aux\con). (In fact, CLOCK$ may be used if an extension is provided.) These restrictions only apply to Windows - Linux, for example, allows use of " * : < > ? \ | even in NTFS.

Source: http://en.wikipedia.org/wiki/Filename

Solution 10 - C#

Rather than explicitly include all possible characters, you could do a regex to check for the presence of illegal characters, and report an error then. Ideally your application should name the files exactly as the user wishes, and only cry foul if it stumbles across an error.

Solution 11 - C#

The question is are you trying to determine if a path name is a legal windows path, or if it's legal on the system where the code is running.? I think the latter is more important, so personally, I'd probably decompose the full path and try to use _mkdir to create the directory the file belongs in, then try to create the file.

This way you know not only if the path contains only valid windows characters, but if it actually represents a path that can be written by this process.

Solution 12 - C#

I use this to get rid of invalid characters in filenames without throwing exceptions:

private static readonly Regex InvalidFileRegex = new Regex(
    string.Format("[{0}]", Regex.Escape(@"<>:""/\|?*")));

public static string SanitizeFileName(string fileName)
{
    return InvalidFileRegex.Replace(fileName, string.Empty);
}

Solution 13 - C#

Also CON, PRN, AUX, NUL, COM# and a few others are never legal filenames in any directory with any extension.

Solution 14 - C#

From MSDN, here's a list of characters that aren't allowed:

>Use almost any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following: > > * The following reserved characters are not allowed: > < > : " / \ | ? * > * Characters whose integer representations are in the range from zero through 31 are not allowed. > * Any other character that the target file system does not allow.

Solution 15 - C#

To complement the other answers, here are a couple of additional edge cases that you might want to consider.

Solution 16 - C#

This is an already answered question, but just for the sake of "Other options", here's a non-ideal one:

(non-ideal because using Exceptions as flow control is a "Bad Thing", generally)

public static bool IsLegalFilename(string name)
{
	try 
	{
		var fileInfo = new FileInfo(name);
		return true;
	}
	catch
	{
		return false;
	}
}

Solution 17 - C#

Regular expressions are overkill for this situation. You can use the String.IndexOfAny() method in combination with Path.GetInvalidPathChars() and Path.GetInvalidFileNameChars().

Also note that both Path.GetInvalidXXX() methods clone an internal array and return the clone. So if you're going to be doing this a lot (thousands and thousands of times) you can cache a copy of the invalid chars array for reuse.

Solution 18 - C#

Also the destination file system is important.

Under NTFS, some files can not be created in specific directories. E.G. $Boot in root

Solution 19 - C#

If you're only trying to check if a string holding your file name/path has any invalid characters, the fastest method I've found is to use Split() to break up the file name into an array of parts wherever there's an invalid character. If the result is only an array of 1, there are no invalid characters. :-)

var nameToTest = "Best file name \"ever\".txt";
bool isInvalidName = nameToTest.Split(System.IO.Path.GetInvalidFileNameChars()).Length > 1;

var pathToTest = "C:\\My Folder <secrets>\\";
bool isInvalidPath = pathToTest.Split(System.IO.Path.GetInvalidPathChars()).Length > 1;

I tried running this and other methods mentioned above on a file/path name 1,000,000 times in LinqPad.

Using Split() is only ~850ms.

Using Regex("[" + Regex.Escape(new string(System.IO.Path.GetInvalidPathChars())) + "]") is around 6 seconds.

The more complicated regular expressions fair MUCH worse, as do some of the other options, like using the various methods on the Path class to get file name and let their internal validation do the job (most likely due to the overhead of exception handling).

Granted it's not very often you need to validation 1 million file names, so a single iteration is fine for most of these methods anyway. But it's still pretty efficient and effective if you're only looking for invalid characters.

Solution 20 - C#

I got this idea from someone. - don't know who. Let the OS do the heavy lifting.

public bool IsPathFileNameGood(string fname)
{
    bool rc = Constants.Fail;
    try
    {
        this._stream = new StreamWriter(fname, true);
        rc = Constants.Pass;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Problem opening file");
        rc = Constants.Fail;
    }
    return rc;
}

Solution 21 - C#

I suggest just use the Path.GetFullPath()

string tagetFileFullNameToBeChecked;
try
{
  Path.GetFullPath(tagetFileFullNameToBeChecked)
}
catch(AugumentException ex)
{
  // invalid chars found
}

Solution 22 - C#

many of these answers will not work if the filename is too long & running on a pre Windows 10 environment. Similarly, have a think about what you want to do with periods - allowing leading or trailing is technically valid, but can create problems if you do not want the file to be difficult to see or delete respectively.

This is a validation attribute I created to check for a valid filename.

public class ValidFileNameAttribute : ValidationAttribute
{
    public ValidFileNameAttribute()
    {
        RequireExtension = true;
        ErrorMessage = "{0} is an Invalid Filename";
        MaxLength = 255; //superseeded in modern windows environments
    }
    public override bool IsValid(object value)
    {
        //http://stackoverflow.com/questions/422090/in-c-sharp-check-that-filename-is-possibly-valid-not-that-it-exists
        var fileName = (string)value;
        if (string.IsNullOrEmpty(fileName)) { return true;  }
        if (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) > -1 ||
            (!AllowHidden && fileName[0] == '.') ||
            fileName[fileName.Length - 1]== '.' ||
            fileName.Length > MaxLength)
        {
            return false;
        }
        string extension = Path.GetExtension(fileName);
        return (!RequireExtension || extension != string.Empty)
            && (ExtensionList==null || ExtensionList.Contains(extension));
    }
    private const string _sepChar = ",";
    private IEnumerable<string> ExtensionList { get; set; }
    public bool AllowHidden { get; set; }
    public bool RequireExtension { get; set; }
    public int MaxLength { get; set; }
    public string AllowedExtensions {
        get { return string.Join(_sepChar, ExtensionList); } 
        set {
            if (string.IsNullOrEmpty(value))
            { ExtensionList = null; }
            else {
                ExtensionList = value.Split(new char[] { _sepChar[0] })
                    .Select(s => s[0] == '.' ? s : ('.' + s))
                    .ToList();
            }
    } }

    public override bool RequiresValidationContext => false;
}

and the tests

[TestMethod]
public void TestFilenameAttribute()
{
	var rxa = new ValidFileNameAttribute();
	Assert.IsFalse(rxa.IsValid("pptx."));
	Assert.IsFalse(rxa.IsValid("pp.tx."));
	Assert.IsFalse(rxa.IsValid("."));
	Assert.IsFalse(rxa.IsValid(".pp.tx"));
	Assert.IsFalse(rxa.IsValid(".pptx"));
	Assert.IsFalse(rxa.IsValid("pptx"));
	Assert.IsFalse(rxa.IsValid("a/abc.pptx"));
	Assert.IsFalse(rxa.IsValid("a\\abc.pptx"));
	Assert.IsFalse(rxa.IsValid("c:abc.pptx"));
	Assert.IsFalse(rxa.IsValid("c<abc.pptx"));
	Assert.IsTrue(rxa.IsValid("abc.pptx"));
	rxa = new ValidFileNameAttribute { AllowedExtensions = ".pptx" };
	Assert.IsFalse(rxa.IsValid("abc.docx"));
	Assert.IsTrue(rxa.IsValid("abc.pptx"));
}

Solution 23 - C#

My attempt:

using System.IO;

static class PathUtils
{
  public static string IsValidFullPath([NotNull] string fullPath)
  {
    if (string.IsNullOrWhiteSpace(fullPath))
      return "Path is null, empty or white space.";

    bool pathContainsInvalidChars = fullPath.IndexOfAny(Path.GetInvalidPathChars()) != -1;
    if (pathContainsInvalidChars)
      return "Path contains invalid characters.";

    string fileName = Path.GetFileName(fullPath);
    if (fileName == "")
      return "Path must contain a file name.";

    bool fileNameContainsInvalidChars = fileName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1;
    if (fileNameContainsInvalidChars)
      return "File name contains invalid characters.";

    if (!Path.IsPathRooted(fullPath))
      return "The path must be absolute.";

    return "";
  }
}

This is not perfect because Path.GetInvalidPathChars does not return the complete set of characters that are invalid in file and directory names and of course there's plenty more subtleties.

So I use this method as a complement:

public static bool TestIfFileCanBeCreated([NotNull] string fullPath)
{
  if (string.IsNullOrWhiteSpace(fullPath))
    throw new ArgumentException("Value cannot be null or whitespace.", "fullPath");

  string directoryName = Path.GetDirectoryName(fullPath);
  if (directoryName != null) Directory.CreateDirectory(directoryName);
  try
  {
    using (new FileStream(fullPath, FileMode.CreateNew)) { }
    File.Delete(fullPath);
    return true;
  }
  catch (IOException)
  {
    return false;
  }
}

It tries to create the file and return false if there is an exception. Of course, I need to create the file but I think it's the safest way to do that. Please also note that I am not deleting directories that have been created.

You can also use the first method to do basic validation, and then handle carefully the exceptions when the path is used.

Solution 24 - C#

In my opinion, the only proper answer to this question is to try to use the path and let the OS and filesystem validate it. Otherwise you are just reimplementing (and probably poorly) all the validation rules that the OS and filesystem already use and if those rules are changed in the future you will have to change your code to match them.

Solution 25 - C#

Windows filenames are pretty unrestrictive, so really it might not even be that much of an issue. The characters that are disallowed by Windows are:

\ / : * ? " < > |

You could easily write an expression to check if those characters are present. A better solution though would be to try and name the files as the user wants, and alert them when a filename doesn't stick.

Solution 26 - C#

This check

static bool IsValidFileName(string name)
{
    return
        !string.IsNullOrWhiteSpace(name) &&
        name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&
        !Path.GetFullPath(name).StartsWith(@"\\.\");
}

filters out names with invalid chars (<>:"/\|?* and ASCII 0-31), as well as reserved DOS devices (CON, NUL, COMx). It allows leading spaces and all-dot-names, consistent with Path.GetFullPath. (Creating file with leading spaces succeeds on my system).


Used .NET Framework 4.7.1, tested on Windows 7.

Solution 27 - C#

One liner for verifying illigal chars in the string:

public static bool IsValidFilename(string testName) => !Regex.IsMatch(testName, "[" + Regex.Escape(new string(System.IO.Path.InvalidPathChars)) + "]");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontomashView Question on Stackoverflow
Solution 1 - C#user7116View Answer on Stackoverflow
Solution 2 - C#Eugene KatzView Answer on Stackoverflow
Solution 3 - C#Steve CooperView Answer on Stackoverflow
Solution 4 - C#Dewayne ChristensenView Answer on Stackoverflow
Solution 5 - C#Scott DormanView Answer on Stackoverflow
Solution 6 - C#Steve CooperView Answer on Stackoverflow
Solution 7 - C#Jon SchneiderView Answer on Stackoverflow
Solution 8 - C#tmtView Answer on Stackoverflow
Solution 9 - C#Martin FaartoftView Answer on Stackoverflow
Solution 10 - C#ConroyPView Answer on Stackoverflow
Solution 11 - C#kfhView Answer on Stackoverflow
Solution 12 - C#JoelFanView Answer on Stackoverflow
Solution 13 - C#Roland RabienView Answer on Stackoverflow
Solution 14 - C#Mark BiekView Answer on Stackoverflow
Solution 15 - C#JoeView Answer on Stackoverflow
Solution 16 - C#JerKimballView Answer on Stackoverflow
Solution 17 - C#s nView Answer on Stackoverflow
Solution 18 - C#Dominik WeberView Answer on Stackoverflow
Solution 19 - C#Nick AlbrechtView Answer on Stackoverflow
Solution 20 - C#KenRView Answer on Stackoverflow
Solution 21 - C#Tony SunView Answer on Stackoverflow
Solution 22 - C#BrentView Answer on Stackoverflow
Solution 23 - C#MaxenceView Answer on Stackoverflow
Solution 24 - C#Igor LevickiView Answer on Stackoverflow
Solution 25 - C#Justin PolieyView Answer on Stackoverflow
Solution 26 - C#VladView Answer on Stackoverflow
Solution 27 - C#ZananokView Answer on Stackoverflow