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

后端 未结 27 1905
-上瘾入骨i
-上瘾入骨i 2020-11-22 09:38

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 n

27条回答
  •  佛祖请我去吃肉
    2020-11-22 10:10

    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

提交回复
热议问题