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
  • 60,845
  • 93
  • 320
  • 589

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
  • 714,442
  • 84
  • 1,110
  • 1,523
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
  • 450,073
  • 74
  • 686
  • 939
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
  • 44,497
  • 23
  • 105
  • 176