C# – Check whether a path is valid

cnetpathwinapi

I am just wondering: I am looking for a way to validate if a given path is valid.
(Note: I do not want to check if a file is existing! I only want to proof the validity of the path – So if a file could possibly exists at the location).

Problem is, I can't find anything in the .Net API.
Due to the many formats and locations that Windows supports, I'd rather use something MS-native.

Since the function should be able to check against:

  • Relative Paths (./)
  • Absolute Paths (c:\tmp)
  • UNC-Pathes (\some-pc\c$)
  • NTFS-Limitations like the full path 1024 chars – If I am not mistaken exceeding the path will make a file inaccessible for many
    internal Windows functions. Renaming it with Explorer still works
  • Volume GUID Paths : "\?\Volume{GUID}\somefile.foo

Does anyone have a function like this?

Best Answer

Try Uri.IsWellFormedUriString():

  • The string is not correctly escaped.

      http://www.example.com/path???/file name
    
  • The string is an absolute Uri that represents an implicit file Uri.

      c:\\directory\filename
    
  • The string is an absolute URI that is missing a slash before the path.

      file://c:/directory/filename
    
  • The string contains unescaped backslashes even if they are treated as forward slashes.

      http:\\host/path/file
    
  • The string represents a hierarchical absolute Uri and does not contain "://".

      www.example.com/path/file
    
  • The parser for the Uri.Scheme indicates that the original string was not well-formed.

      The example depends on the scheme of the URI.