Validate folder name in C#

前端 未结 3 988
夕颜
夕颜 2020-12-19 05:55

I need to validate a folder name in c#.

I have tried the following regex :

 ^(.*?/|.*?\\\\)?([^\\./|^\\.\\\\]+)(?:\\.([^\\\\]*)|)$
<
3条回答
  •  情话喂你
    2020-12-19 05:55

    You could do that in this way (using 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;
    }
    

    [edit]
    If you want a regular expression that validates a folder path, then you could use this one:

    Regex regex = new Regex("^([a-zA-Z]:)?(\\\\[^<>:\"/\\\\|?*]+)+\\\\?$");

    [edit 2]
    I've remembered one tricky thing that lets you check if the path is correct:

    var invalidPathChars = Path.GetInvalidPathChars(path)

    or (for files):

    var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)

提交回复
热议问题