通过C#确定string是否是有效的文件path

我想知道如何确定string是否是有效的文件path。

文件path可能存在也可能存在。

对path的string格式进行100%准确的检查是非常困难的,因为它取决于使用它的文件系统(以及networking协议,如果它不在同一台计算机上)。

即使在windows甚至是NTFS中也不是那么简单,因为它仍然依赖于.NET在后台使用的API来与内核通信。

由于目前大多数文件系统都支持unicode,所以也可能需要检查所有的规则,比如正确编码的unicode,规范化等等。

我要做的只是做一些基本的检查,然后一旦使用path正确处理exception。 有关可能的规则请参阅

  • 维基百科 – 文件名以概述不同文件系统使用的规则
  • 命名窗口特定规则的文件,path和命名空间

您可以使用FileInfo构造函数。 如果“文件名为空,仅包含空白或包含无效字符,它将引发ArgumentException”。 它也可以抛出SecurityException或UnauthorizedAccessException,我认为如果你只关心格式,你可以忽略它。

另一种select是直接检查Path.GetInvalidPathChars 。 例如:

boolean possiblePath = pathString.IndexOfAny(Path.GetInvalidPathChars()) == -1; 

这里有一些你可能会用到的东西:

  • 检查驱动器是否正确(例如,在一台计算机上的驱动器X:\存在,但不是在你的):使用Path.IsPathRooted ,看看它不是一个相对path,然后使用Environment.GetLogicalDrives()看看你的path是否包含其中一个有效的驱动器。
  • 要检查有效字符,有两个方法: Path.GetInvalidFileNameChars()Path.GetInvalidPathChars() ,它们不完全重叠。 您也可以使用Path.GetDirectoryName(path)Path.GetFileName(fileName)与您的input名称,这将引发exception如果

path参数包含无效字符,为空或仅包含空格。

你不能确定,直到你尝试创build该文件。 也许path是有效的,但安全设置不允许创build文件。 唯一的例子可以告诉你,如果path是真正有效的将是操作系统,所以为什么不尝试创build该文件赶上IOException它指出什么是真的错了? Imho这是更简单的方法:假设input是有效的,如果没有做任何事情,而不是做很多不必要的工作。

你尝试过正则expression式吗?

 ^([a-zA-Z]\:)(\\[^\\/:*?<>"|]*(?<![ ]))*(\.[a-zA-Z]{2,6})$ 

应该pipe用

试试这个方法,试图覆盖所有可能的例外情况。 它几乎适用于所有与Windows相关的path。

 /// <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; } 
 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; } 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 directoryInfo = new DirectoryInfo(Path.GetFullPath(path)); try { if (!directoryInfo.Exists) { directoryInfo.Create(); } } catch (Exception ex) { if (Log.IsErrorEnabled) { Log.Error(ex.Message); } return false; }`enter code here` return true; } 

我在Dgery Borysov的regexlib.com( http://regexlib.com/REDetails.aspx?regexp_id=345 )发现了这个。

“文件名validation器。validationUNC(\ server \ share \ file)和常规MSpath(c:\ file)”

 ^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?))\\)*[^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?$ 

用Regex.IsMatch运行它,你会得到一个bool指示它是否有效。 我认为正则expression式是要走的路,因为文件可能不存在。

您可以简单地在try catch语句中使用Path.Combine():

 string path = @" your path "; try { Path.Combine(path); } catch { MessageBox.Show("Invalid path"); } 

编辑:请注意,如果path包含通配符('*'和'?'),则此函数不会引发exception,因为它们可以在searchstring中使用。

静态类System.IO.Path可以做你所要求的。