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
  • 52,885
  • 84
  • 282
  • 517

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
  • 675,664
  • 71
  • 998
  • 1,399
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
  • 411,418
  • 61
  • 614
  • 859
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
  • 42,665
  • 20
  • 93
  • 158