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

后端 未结 27 1712
-上瘾入骨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:34

    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.

提交回复
热议问题