[英]Regex to validate a Windows UNC path
I am trying to validate a Windows path in c# using a regex. 我正在尝试使用正则表达式在c#中验证Windows路径。 Based on this answer https://stackoverflow.com/a/24703223/4264336 I have come up with a regex that allows drive letters & unc paths but it seems to choke on spaces.
基于这个答案https://stackoverflow.com/a/24703223/4264336我提出了一个允许驱动器字母和非路径的正则表达式,但它似乎在空格上窒息。
The Function: 功能:
public bool ValidatePath(string path)
{
Regex regex = new Regex(@"^(([a-zA-Z]:\\)|\\\\)(((?![<>:""/\\|? *]).)+((?<![ .])\\)?)*$");
return regex.IsMatch(path);
}
which works for all my test cases except the case where spaces are in the filename: 这适用于我的所有测试用例,除了文件名中有空格的情况:
[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);
}
how do I get it to allow spaces in filenames, I cant for the life of me see where to add it? 如何让它允许文件名中的空格,我不能在我的生活中看到在哪里添加它?
You can already do this in the .NET Framework by creating a Uri and using the Uri.IsUnc property . 您可以通过创建Uri并使用Uri.IsUnc属性在.NET Framework中执行此操作。
Uri uncPath = new Uri(@"\\my\unc\path");
Console.WriteLine(uncPath.IsUnc);
Furthermore you can see how this is implemented in the reference source . 此外,您可以在参考源中看到它是如何实现的。
Windows disallows a few characters: Windows不允许使用几个字符:
Specified here: Microsoft Docs: Naming Files, Paths, and Namespaces 在此处指定: Microsoft Docs:命名文件,路径和命名空间
So here is an exclusion base regular expression for UNC 所以这是UNC的排除基础正则表达式
(\\\\([a-z|A-Z|0-9|-|_|\s]{2,15}){1}(\.[a-z|A-Z|0-9|-|_|\s]{1,64}){0,3}){1}(\\[^\\|\/|\:|\*|\?|"|\<|\>|\|]{1,64}){1,}(\\){0,}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.