检查一个string是否是有效的Windows目录(文件夹)path

我试图确定一个用户input的string是否有效表示一个文件夹的path。 有效的,我的意思是格式正确。

在我的应用程序中,该文件夹代表安装目标。 假设文件夹path有效的,我想确定文件夹是否存在,如果不存在,就创build它。

我目前使用IO.Directory.Exists( String path ) 。 我发现这工作正常,除非用户不正确格式化string。 发生这种情况时,此方法将返回false,表示该文件夹不存在。 但这是一个问题,因为我以后无法创build文件夹。

从我的谷歌search,我发现了一个build议,使用正则expression式来检查格式是否正确。 我没有正则expression式的经验,我想知道这是否是一个可行的方法。 这是我发现的:

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

将正则expression式testing与Directory.Exists()结合起来,给我一个足够好的方法来检查path是否有效,是否存在? 我知道这将随着操作系统和其他因素而变化,但该程序仅针对Windows用户。

调用Path.GetFullPath ; 如果path无效,它将会抛出exception。

要禁止相对path(如Word ),请调用Path.IsPathRooted

我其实不同意SLaks。 这个解决scheme对我不起作用。 exception没有按预期发生。 但是这个代码为我工作:

 if(System.IO.Directory.Exists(path)) { ... } 

Path.GetFullPath只给出下面的例外

ArgumentException path是一个长度为零的string,仅包含空格,或者包含GetInvalidPathChars中定义的一个或多个无效字符。 – 或者 – 系统无法检索绝对path。

SecurityException调用方不具有所需的权限。

ArgumentNullExceptionpath为null。

NotSupportedExceptionpath包含不属于卷标识符(例如“c:\”)的冒号(“:”)。

PathTooLongException指定的path,文件名或两者超出系统定义的最大长度。 例如,在基于Windows的平台上,path必须less于248个字符,文件名必须less于260个字符。

另一种方法是使用以下内容:

 /// <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; } 

使用此代码

 string DirectoryName = "Sample Name For Directory Or File"; Path.GetInvalidFileNameChars().Where(x => DirectoryName.Contains(x)).Count() > 0 || DirectoryName == "con" 
  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; } 

这是一个解决scheme,利用了@SLaks 的回答中推荐的Path.GetFullPath 。

在我这里包括的代码中,请注意IsValidPath(string path)被devise为使得调用者不必担心exception处理

您也可能会发现它调用的方法TryGetFullPath(...) ,当您希望安全地尝试获取绝对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; }