在C#中验证文件夹名称

Nid*_*har 7 c# regex

我需要在c#中验证文件夹名称.

我试过以下正则表达式:

 ^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$
Run Code Online (Sandbox Code Playgroud)

但它失败了,我也尝试过使用GetInvalidPathChars().

当我尝试使用P:\abc文件夹名称时失败,即Driveletter:\foldername

谁有人建议为什么?

Nic*_*kon 12

你可以这样做(使用System.IO.Path.InvalidPathChars常量):

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;
}
Run Code Online (Sandbox Code Playgroud)

[edit]
如果你想要一个验证文件夹路径的正则表达式,那么你可以使用这个:

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

[编辑2]
我记得有一个棘手的事情让你检查路径是否正确:

var invalidPathChars = Path.GetInvalidPathChars(path)

或(对于文件):

var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)