I am trying to validate a Windows path in c# using a regex. 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.
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 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:
Specified here: Microsoft Docs: Naming Files, Paths, and Namespaces
So here is an exclusion base regular expression for 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,}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With