0

.NET methods like Path.IsPathRooted() are great, but throw if the input string isn't valid. Which is fine, but it would be nice to pre-check if an input string is a valid path before jumping into an exception-checking codeblock.

I can't see a Path.IsValidPath() or similar, is there something like this available?

Mr. Boy
  • 57,008
  • 88
  • 294
  • 540

3 Answers3

1

According to the documentation,

ArgumentException [is thrown when] path contains one or more of the invalid characters defined in GetInvalidPathChars.

This means that you can pre-validate your path strings as follows:

if (path.IndexOfAny(Path.GetInvalidPathChars()) != -1) {
    // This means that Path.IsPathRooted will throw an exception
    ....
}

This is the only condition under which IsPathRooted throws an exception.

Take a look at Mono source of Path.cs, line 496, for details on how this is implemented.

Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
1

You could use File.Exists or Directory.Exists.

If you want to check if a path contains illegal chars (on NET 2.0) you can use Path.GetInvalidPathChars:

char[] invalidChars = System.IO.Path.GetInvalidPathChars();
bool valid = path.IndexOfAny(invalidChars) != -1;
Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891
0
public bool ValidPathString(string path)
{
    if (string.IsNullOrEmpty(path)) return false;
    char[] invalidPathChars = System.IO.Path.GetInvalidPathChars();
    foreach (char c in invalidPathChars)
    {
        if(path.Contains(c)) return false;
    }
    return true;
}
paparazzo
  • 43,659
  • 20
  • 99
  • 164