用于验证Windows UNC路径的正则表达式

4
我将使用正则表达式在C#中验证Windows路径。根据这个答案https://dev59.com/9oHba4cB1Zd3GeqPRXEL#24703223,我已经想出了一个允许驱动器字母和UNC路径的正则表达式,但似乎无法处理空格。
该函数:
public bool ValidatePath(string path)
    {
        Regex regex = new Regex(@"^(([a-zA-Z]:\\)|\\\\)(((?![<>:""/\\|? *]).)+((?<![ .])\\)?)*$");
        return regex.IsMatch(path);
    }

这种方法对我所有的测试用例都有效,但是在文件名中包含空格的情况下无法正常工作:

    [Test]
    [TestCase(@"c:\", true)]
    [TestCase(@"\\server\filename", true)]
    [TestCase(@"\\server\filename with space", true)] //fails
    [TestCase(@"\\server\filename\{token}\file", true)] 
    [TestCase(@"zzzzz", false)]
    public void BadPathTest(string path, bool expected) 
    {
        ValidatePath(path).Should().Be(expected);
    }

如何让文件名中允许空格?我无论如何都找不到添加的地方。


1
所以,如果允许的话,请在模式中删除空格 - Wiktor Stribiżew
谢谢@WiktorStribiżew_,我刚刚浪费了很长时间看错了空格! - Lobsterpants
正则表达式很混乱,请不要使用它。 - Wiktor Stribiżew
2个回答

8

在.NET Framework中,您可以通过创建Uri并使用Uri.IsUnc属性来实现此操作。

Uri uncPath =  new Uri(@"\\my\unc\path");
Console.WriteLine(uncPath.IsUnc);

此外,您可以查看此实现在参考源码中的具体实现。

1
不是我想要的,但对其他人很有用。 - Lobsterpants

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接