Check the correct path

I'm just curious: I'm looking for a way to check if a given path is valid. (Note: I do not want to check if the file exists! I only want to check the path is correct - so if the file can exist in this place).

The problem is that I cannot find anything in API.Net. Due to the large number of formats and locations supported by Windows, I would rather use something MS-native.

Since the function should be able to check:

  • Relative paths (./)
  • Absolute paths (c: \ tmp)
  • UNC-Pathes (\ some-pc \ c $)
  • NTFS restrictions, such as the full path of 1024 characters - if I am not mistaken, exceeding the path will make the file inaccessible to many internal functions of Windows. Renaming it with Explorer still works
  • Volume GUID paths: "\? \ Volume {GUID} \ somefile.foo

Does anyone have such a feature?

+75
c # winapi path
Jun 01 2018-11-11T00:
source share
10 answers

Try Uri.IsWellFormedUriString() :

  • The string is incorrectly escaped.

     http://www.example.com/path???/file name 
  • A string is an absolute Uri, which is an implicit Uri file.

     c:\\directory\filename 
  • A string is an absolute URI that does not have a slash in front of the path.

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

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

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

     The example depends on the scheme of the URI. 
+48
Jun 01 2018-11-11T00:
source share

Or use FileInfo as suggested in C #, verify that the file name is possibly valid (does not exist) .

+19
Jun 01 2018-11-11T00:
source share
 private bool IsValidPath(string path) { Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$"); if (!driveCheck.IsMatch(path.Substring(0, 3))) return false; string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars()); strTheseAreInvalidFileNameChars += @":/?*" + "\""; Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]"); if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3))) return false; DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path)); if (!dir.Exists) dir.Create(); return true; } 
+6
Sep 27 '14 at 6:26
source share

The closest I came, trying to create it and see if it succeeds.

+3
Jun 01 '11 at 8:45
source share

You can try this code:

 try { Path.GetDirectoryName(myPath); } catch { // Path is not valid } 

I'm not sure that it covers all cases ...

+3
Oct. 12 '14 at 11:15
source share
+2
Jun 01 2018-11-11T00:
source share

Get invalid characters from System.IO.Path.GetInvalidPathChars(); and check if your string contains (directory path) or not.

+1
Jun 01 2018-11-11T00:
source share

Try this method

 /// <summary> /// Validate the Path. If path is relative append the path to the project directory by default. /// </summary> /// <param name="path">Path to validate</param> /// <param name="RelativePath">Relative path</param> /// <param name="Extension">If want to check for File Path</param> /// <returns></returns> private static bool ValidateDllPath(ref string path, string RelativePath = "", string Extension = "") { // Check if it contains any Invalid Characters. if (path.IndexOfAny(Path.GetInvalidPathChars()) == -1) { try { // If path is relative take %IGXLROOT% as the base directory if (!Path.IsPathRooted(path)) { if (string.IsNullOrEmpty(RelativePath)) { // Exceptions handled by Path.GetFullPath // ArgumentException path is a zero-length string, contains only white space, or contains one or more of the invalid characters defined in GetInvalidPathChars. -or- The system could not retrieve the absolute path. // // SecurityException The caller does not have the required permissions. // // ArgumentNullException path is null. // // NotSupportedException path contains a colon (":") that is not part of a volume identifier (for example, "c:\"). // PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. // RelativePath is not passed so we would take the project path path = Path.GetFullPath(RelativePath); } else { // Make sure the path is relative to the RelativePath and not our project directory path = Path.Combine(RelativePath, path); } } // Exceptions from FileInfo Constructor: // System.ArgumentNullException: // fileName is null. // // System.Security.SecurityException: // The caller does not have the required permission. // // System.ArgumentException: // The file name is empty, contains only white spaces, or contains invalid characters. // // System.IO.PathTooLongException: // The specified path, file name, or both exceed the system-defined maximum // length. For example, on Windows-based platforms, paths must be less than // 248 characters, and file names must be less than 260 characters. // // System.NotSupportedException: // fileName contains a colon (:) in the middle of the string. FileInfo fileInfo = new FileInfo(path); // Exceptions using FileInfo.Length: // System.IO.IOException: // System.IO.FileSystemInfo.Refresh() cannot update the state of the file or // directory. // // System.IO.FileNotFoundException: // The file does not exist.-or- The Length property is called for a directory. bool throwEx = fileInfo.Length == -1; // Exceptions using FileInfo.IsReadOnly: // System.UnauthorizedAccessException: // Access to fileName is denied. // The file described by the current System.IO.FileInfo object is read-only.-or- // This operation is not supported on the current platform.-or- The caller does // not have the required permission. throwEx = fileInfo.IsReadOnly; if (!string.IsNullOrEmpty(Extension)) { // Validate the Extension of the file. if (Path.GetExtension(path).Equals(Extension, StringComparison.InvariantCultureIgnoreCase)) { // Trim the Library Path path = path.Trim(); return true; } else { return false; } } else { return true; } } catch (ArgumentNullException) { // System.ArgumentNullException: // fileName is null. } catch (System.Security.SecurityException) { // System.Security.SecurityException: // The caller does not have the required permission. } catch (ArgumentException) { // System.ArgumentException: // The file name is empty, contains only white spaces, or contains invalid characters. } catch (UnauthorizedAccessException) { // System.UnauthorizedAccessException: // Access to fileName is denied. } catch (PathTooLongException) { // System.IO.PathTooLongException: // The specified path, file name, or both exceed the system-defined maximum // length. For example, on Windows-based platforms, paths must be less than // 248 characters, and file names must be less than 260 characters. } catch (NotSupportedException) { // System.NotSupportedException: // fileName contains a colon (:) in the middle of the string. } catch (FileNotFoundException) { // System.FileNotFoundException // The exception that is thrown when an attempt to access a file that does not // exist on disk fails. } catch (IOException) { // System.IO.IOException: // An I/O error occurred while opening the file. } catch (Exception) { // Unknown Exception. Might be due to wrong case or nulll checks. } } else { // Path contains invalid characters } return false; } 
-one
Feb 12 '15 at 6:22
source share
 private bool IsValidPath(string path) { Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$"); if (string.IsNullOrWhiteSpace(path) || path.Length < 3) { return false; } if (!driveCheck.IsMatch(path.Substring(0, 3))) { return false; } var x1 = (path.Substring(3, path.Length - 3)); string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars()); strTheseAreInvalidFileNameChars += @":?*"; Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]"); if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3))) { return false; } var driveLetterWithColonAndSlash = Path.GetPathRoot(path); if (!DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash)) { return false; } return true; } 
-one
Oct 31 '16 at 12:54
source share

You can try using Path.IsPathRooted () in combination with Path.GetInvalidFileNameChars () to make sure the path halfway is in order.

-3
Feb 06 '13 at 17:30
source share



All Articles