在C#中检查文件名是*可能*有效(不是它存在)

System.IO名称空间中是否有方法检查文件名的有效性?

例如, C:\foo\bar会validation并且:"~-*不会

或者有点麻烦, X:\foo\bar会validation系统上是否有一个X:驱动器,否则不会。

我想我可以自己写一个这样的方法,但是我对一个内置的方法更感兴趣。

做就是了;

 System.IO.FileInfo fi = null; try { fi = new System.IO.FileInfo(fileName); } catch (ArgumentException) { } catch (System.IO.PathTooLongException) { } catch (NotSupportedException) { } if (ReferenceEquals(fi, null)) { // file name is not valid } else { // file name is valid... May check for existence by calling fi.Exists. } 

为了创buildFileInfo实例,文件不需要存在。

您可以从此问题中讨论的Path.GetInvalidPathChars和GetInvalidFileNameChars获取无效字符的列表。

正如jberger所指出的那样,还有一些其他字符不包含在这个方法的响应中。 有关Windows平台的更多详细信息,请查看MSDN上的命名文件,path和命名空间 ,

正如Micah 指出的那样 ,有Directory.GetLogicalDrives来获取有效驱动器的列表。

System.IO名称空间中存在几种可用的方法:

 Directory.GetLogicalDrives() // Returns an array of strings like "c:\" Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path. 

build议你可以这样做:

 bool IsValidFilename(string testName) { string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]"; Regex containsABadCharacter = new Regex(regexString); if (containsABadCharacter.IsMatch(testName)) { return false; } // Check for drive string pathRoot = Path.GetPathRoot(testName); if (Directory.GetLogicalDrives().Contains(pathRoot)) { // etc } // other checks for UNC, drive-path format, etc return true; } 

你可以使用System.Uri类。 Uri类不仅适用于Web URL,还可处理文件系统path。 使用Uri.TryCreate方法来查找path是否为根,然后使用IsLoopback属性来确定Uri是否引用本地计算机。

这是一个简单的方法,它确定一个string是否是一个有效的本地和根文件path。

 public bool IsPathValidRootedLocal(String pathString) { Uri pathUri; Boolean isValidUri = Uri.TryCreate(pathString, UriKind.Absolute, out pathUri); return isValidUri && pathUri != null && pathUri.IsLoopback; } 

我相信这会起作用。

即使文件名是有效的,您仍然可能想要touch它以确保用户有权写入。

如果你不会在短时间内用数百个文件来破坏磁盘,我认为创build一个空文件是一个合理的方法。

如果你真的想要更轻的东西,比如只检查无效的字符,那么比较你的文件名和Path.GetInvalidFileNameChars()。

如果path或文件名无效,几个System.IO.Path方法将引发exception:

  • Path.IsPathRooted()
  • Path.GetFileName()

http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx

以为我会发布一个解决scheme,我拼凑在一起,find了解决同样的问题后,find了一些答案。 希望它可以帮助别人。

 using System; using System.IO; //.. public static bool ValidateFilePath(string path,bool RequireDirectory,bool IncludeFileName,bool RequireFileName=false) { if (string.IsNullOrEmpty(path)) {return false;} string root = null; ; string directory=null; string filename=null; try { //throw ArgumentException - The path parameter contains invalid characters, is empty, or contains only white spaces. root = Path.GetPathRoot(path); //throw ArgumentException - path contains one or more of the invalid characters defined in GetInvalidPathChars. // -or- String.Empty was passed to path. directory = Path.GetDirectoryName(path); //path contains one or more of the invalid characters defined in GetInvalidPathChars if (IncludeFileName) { filename = Path.GetFileName(path); } } catch (ArgumentException) { return false; } //null if path is null, or an empty string if path does not contain root directory information if (String.IsNullOrEmpty(root)){return false;} //null if path denotes a root directory or is null. Returns String.Empty if path does not contain directory information if (String.IsNullOrEmpty(directory)) { return false; } if (RequireFileName) { //f the last character of path is a directory or volume separator character, this method returns String.Empty if (String.IsNullOrEmpty(filename)) { return false; } //check for illegal chars in filename if (filename.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0){ return false;} } return true; } 

System.IO命名空间的Path类中使用静态GetInvalidFileNameChars方法来确定文件名中的哪些字符是非法的。

要在path中执行此操作,请调用同一个类上的静态GetInvalidPathChars方法 。

要确定path的根是否有效,可以调用Path类的静态GetPathRoot方法来获取根,然后使用Directory类来确定它是否有效。 然后,您可以正常validationpath的其余部分。

这将使您获得机器上的驱动器:

 System.IO.DriveInfo.GetDrives() 

这两个方法会让你查错的字符:

 System.IO.Path.GetInvalidFileNameChars(); System.IO.Path.GetInvalidPathChars(); 

正如其他人所表明的那样,我运用了正则expression式。

有一件事要记住,Windows至less禁止一些文件名,否则包含法律字符。 有几个想到:com,nul,prn。

我现在没有和我在一起,但我有一个正则expression式,考虑到这些文件名。 如果你想我可以发布,否则我相信你可以find我的方式:谷歌。

-Jay

我不知道任何可以validation所有这一切的开箱即用,但是.NETPath类可以帮助您大大提高。

对于初学者来说,它有:

 char[] invalidChars = Path.GetInvalidFileNameChars(); //returns invalid charachters 

要么:

 Path.GetPathRoot(string); // will return the root. 

试试这个方法,试图覆盖所有可能的例外情况。 它几乎适用于所有与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; } 

可能的麻烦方法是build立一个自定义的方法混合正则expression式和小文件在您的文件系统上查找(例如查看驱动器)

认为现在回答已经太迟了,但是… :)如果有卷名的path,你可以这样写:

 using System; using System.Linq; using System.IO; // ... var drives = Environment.GetLogicalDrives(); var invalidChars = Regex.Replace(new string(Path.GetInvalidFileNameChars()), "[\\\\/]", ""); var drive = drives.FirstOrDefault(d => filePath.StartsWith(d)); if (drive != null) { var fileDirPath = filePath.Substring(drive.Length); if (0 < fileDirPath.Length) { if (fileDirPath.IndexOfAny(invalidChars.ToCharArray()) == -1) { if (Path.Combine(drive, fileDirPath) != drive) { // path correct and we can proceed } } } }