2010-06-18 85 views
36

我想知道如何确定字符串是否是有效的文件路径。通过C#确定字符串是否是有效的文件路径

文件路径可能或可能是而不是存在。

+1

你是说你有一个字符串,它看起来像一个路径,以及是否该文件确实存在,你要知道,如果在给定的“路径”文件可能存在吗?如果路径有效,即使该位置没有文件? – SqlRyan 2010-06-18 06:00:04

+0

可能的重复[如何检查给定的字符串是合法(允许)在Windows下的文件名吗?](http://stackoverflow.com/questions/62771/how-check-if-given-string-is-legal-allowed-文件名下的窗口) – nawfal 2013-06-05 11:52:44

+0

如果您的关注更一般地测试一个字符串是否可以代表一个文件***或***文件夹,请参阅[这个答案](http://stackoverflow.com/a/3137165/1497596)或[与此相关的答案](http://stackoverflow.com/a/41049011/1497596)。 – DavidRR 2016-12-08 21:33:41

回答

18

路径的字符串格式的100%准确的检查是相当困难的,因为这将取决于文件系统上使用它(和网络协议,如果它不是在同一台计算机上)。

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

而且,由于今天大多数文件系统支持Unicode,一个可能还需要检查所有的规则,正确地将编码的Unicode,规范化,等等等等

我今天准备先做一个只有一些基本的检查,那么一旦使用路径,就会正确处理异常。对于可能的规则请参见:

+0

其维基百科;) – atamanroman 2010-06-18 08:39:20

+1

:-)感谢fielding,修复它。 – Stefan 2010-06-18 09:07:31

44

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

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

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

FWIW,这将返回误报。您还需要检查权限,并且文件夹/文件名不是非法的(http://en.wikipedia.org/wiki/DOS#Reserved_device_names)。 – 2010-06-18 08:17:30

+0

'新的FileInfo(“test”)'是完全有效的,但不是一个文件。 – Julien 2017-08-11 20:45:48

+1

@Julien如果不传入完整路径,它会将它视为从'Directory.GetCurrentDirectory()'返回的任何内容的相对路径。因此,如果你正在'C:\ Temp'中工作,并且你调用'new FileInfo(“test”);',FullName'属性将是'C:\ Temp \ test'。 – tehDorf 2017-11-08 19:53:05

2

您是否尝试过正则表达式?

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

应该工作

+1

他从来没有说过绝对路径,文件扩展名长度没有限制,而且不是可移植的。 – 2010-06-18 06:04:36

+39

有些人遇到问题时,会想:“我知道,我会用正则表达式。”现在他们有两个问题。 -Jamie Zawinski – womp 2010-06-18 06:27:35

0

我发现这个在regexlib.com(http://regexlib.com/REDetails.aspx?regexp_id=345)由梅德Borysov概述。

“文件名验证既证明了UNC(\服务器\共享\文件),并定期MS路径(C:\文件)”

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

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

0

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

8

这里有一些东西,你可以使用:

  • 检查,如果驱动器是正确的(例如一台计算机上的驱动器X:\存在,但不会对你的):使用Path.IsPathRooted,看它是否是而不是相对路径,然后使用Environment.GetLogicalDrives()中的驱动器查看您的路径是否包含有效驱动器之一。
  • 要检查有效字符,您有两种方法:Path.GetInvalidFileNameChars()Path.GetInvalidPathChars(),它们不完全重叠。您还可以使用Path.GetDirectoryName(path)Path.GetFileName(fileName)你输入名称,它将throw an exception如果

路径参数包含无效字符,为空,或者只包含空格。

3

直到尝试创建该文件时,才能真正确定。也许路径是有效的,但安全设置不允许创建文件。唯一可以告诉你路径是否真正有效的实例是操作系统,那么为什么不尝试创建该文件,赶上IOException,这表明事情真的发生了错误? Imho这是更简单的方法:假设输入是有效的,并且如果它没有做什么,而不是做很多不必要的工作。

0

您可以简单地使用Path.Combine()一个try catch语句里面:

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

编辑: 需要注意的是,如果路径中包含通配符此功能不会抛出异常( '*'和'?'),因为它们可以在搜索字符串中使用。

+0

这实际上并没有赶上当我的路径是“非法的东西” – MichaelvdNet 2013-10-08 15:33:46

1

尝试使用此方法将尝试涵盖所有可能的异常情况。它几乎适用于所有与Windows相关的路径。

/// <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; 
} 
1
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; 
    } 
+0

这适用于我..即使该位置不存在PC – 2016-10-31 09:22:41

相关问题