Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to validate a Windows UNC path

Tags:

c#

regex

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?

like image 241
Lobsterpants Avatar asked Mar 06 '23 20:03

Lobsterpants


2 Answers

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.

like image 95
Owen Pauling Avatar answered Mar 10 '23 09:03

Owen Pauling


Windows disallows a few characters:

enter image description here

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,}
like image 44
Daniel Fisher lennybacon Avatar answered Mar 10 '23 09:03

Daniel Fisher lennybacon