6

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?

4

2 Answers 2

8

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.

1
  • 1
    Not really what I want to do thanks, but a useful answer for others. Commented Jul 12, 2018 at 12:29
5

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,}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.