4

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?

Lobsterpants
  • 1,188
  • 2
  • 13
  • 33
  • 1
    So, [remove the spaces](https://regex101.com/r/k51PRy/1) in the pattern if you allow them. – Wiktor Stribiżew Jul 12 '18 at 12:21
  • Thankyou @WiktorStribiżew _ had just spent ages looking at the wrong space! – Lobsterpants Jul 12 '18 at 12:27
  • The regex is a mess, do not use it. – Wiktor Stribiżew Jul 12 '18 at 12:36
  • Probably, it can be pruned to [`^(?:[a-zA-Z]:\\|\\\\)(?>[^\r\n<>:"/\\|?*]+(?:(?<![\s.])\\)?)+$`](http://regexstorm.net/tester?p=%5e%28%3f%3a%5ba-zA-Z%5d%3a%5c%5c%7c%5c%5c%5c%5c%29%28%3f%3e%5b%5e%5cr%5cn%3c%3e%3a%22%2f%5c%5c%7c%3f*%5d%2b%28%3f%3a%28%3f%3c!%5b%5cs.%5d%29%5c%5c%29%3f%29%2b%5cr%3f%24&i=c%3a%5c%0d%0a%5c%5cserver%5cfilename%0d%0a%5c%5cserver%5cfilename+with+space%0d%0a%5c%5cserver%5cfilename%5c%7btoken%7d%5cfile%0d%0a%0d%0azzzzz%0d%0a&o=m). Still, use the right tool for it. – Wiktor Stribiżew Jul 12 '18 at 12:45

2 Answers2

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.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
4

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,}
Daniel Fisher lennybacon
  • 3,865
  • 1
  • 30
  • 38