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?
^(?:[a-zA-Z]:\\|\\\\)(?>[^\r\n<>:"/\\|?*]+(?:(?<![\s.])\\)?)+$
. Still, use the right tool for it.