Check the correct line in the Windows directory (folder)

I am trying to determine if the string entered by the user to represent the folder path is valid. In fact, I mean formatted properly.

In my application, the folder represents the installation location. If the folder path is valid, I want to determine if the folder exists and create it if it is not.

I am currently using IO.Directory.Exists( String path ) . I believe this works great if the user does not format the string correctly. When this happens, this method will return false, which indicates that the folder does not exist. But this is a problem, because subsequently I will not be able to create the folder.

From my search query, I found a suggestion to use a regular expression to validate the format. I have no experience with regular expressions and I wonder if this is a viable approach. Here is what I found:

 Regex r = new Regex( @"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$" ); return r.IsMatch( path ); 

Will the regex test combined with Directory.Exists() give me a good enough way to check if the path is valid and does it exist? I know that this will differ from the OS and other factors, but the program is intended only for Windows users.

+57
c # windows filesystems validation folder
Jun 29 '10 at 0:32
source share
6 answers

Call Path.GetFullPath ; it will throw exceptions if the path is invalid.

To disable relative paths (e.g., Word ), call Path.IsPathRooted .

+78
Jun 29 2018-10-06T00:
source share

I really disagree with SLaks. This solution did not work for me. The exception did not happen as expected. But this code worked for me:

 if(System.IO.Directory.Exists(path)) { ... } 
+18
May 13 '13 at 16:02
source share

Path.GetFullPath provides exceptions only

The ArgumentException path is a zero-length string, contains only white space, or contains one or more invalid characters defined in GetInvalidPathChars. -or- The system could not get the absolute path.

SecurityException The caller does not have the required permissions.

ArgumentNullException is null.

The NotSupportedException path contains a colon (":"), which is not part of the volume identifier (for example, "c: \").

PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. For example, based on the Windows platform, paths must be less than 248 characters, and file names must be less than 260 characters.

An alternative way is to use the following:

 /// <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; } 
+8
Feb 12 '15 at 6:21
source share

Use this code

 string DirectoryName = "Sample Name For Directory Or File"; Path.GetInvalidFileNameChars().Where(x => DirectoryName.Contains(x)).Count() > 0 || DirectoryName == "con" 
+5
Sep 05 '12 at 11:52
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; } 
+4
Sep 27 '14 at 6:25
source share

Here is a solution that uses Path.GetFullPath as recommended in @SLaks answer .

In the code that I include here, note that IsValidPath(string path) designed in such a way that the caller does not need to worry about handling exceptions .

You may also find that the method it calls, TryGetFullPath(...) , also has its merits when you want to safely try to get the absolute path .

 /// <summary> /// Gets a value that indicates whether <paramref name="path"/> /// is a valid path. /// </summary> /// <returns>Returns <c>true</c> if <paramref name="path"/> is a /// valid path; <c>false</c> otherwise. Also returns <c>false</c> if /// the caller does not have the required permissions to access /// <paramref name="path"/>. /// </returns> /// <seealso cref="Path.GetFullPath"/> /// <seealso cref="TryGetFullPath"/> public static bool IsValidPath(string path) { string result; return TryGetFullPath(path, out result); } /// <summary> /// Returns the absolute path for the specified path string. A return /// value indicates whether the conversion succeeded. /// </summary> /// <param name="path">The file or directory for which to obtain absolute /// path information. /// </param> /// <param name="result">When this method returns, contains the absolute /// path representation of <paramref name="path"/>, if the conversion /// succeeded, or <see cref="String.Empty"/> if the conversion failed. /// The conversion fails if <paramref name="path"/> is null or /// <see cref="String.Empty"/>, or is not of the correct format. This /// parameter is passed uninitialized; any value originally supplied /// in <paramref name="result"/> will be overwritten. /// </param> /// <returns><c>true</c> if <paramref name="path"/> was converted /// to an absolute path successfully; otherwise, false. /// </returns> /// <seealso cref="Path.GetFullPath"/> /// <seealso cref="IsValidPath"/> public static bool TryGetFullPath(string path, out string result) { result = String.Empty; if (String.IsNullOrWhiteSpace(path)) { return false; } bool status = false; try { result = Path.GetFullPath(path); status = true; } catch (ArgumentException) { } catch (SecurityException) { } catch (NotSupportedException) { } catch (PathTooLongException) { } return status; } 
+4
Dec 08 '16 at 21:20
source share



All Articles