代码之家  ›  专栏  ›  技术社区  ›  Diskdrive

通过c确定字符串是否是有效的文件路径

  •  41
  • Diskdrive  · 技术社区  · 14 年前

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

    文件路径可以 存在。

    10 回复  |  直到 8 年前
        1
  •  21
  •   Stefan    14 年前

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

    即使在Windows甚至是NTFS中,它也不简单,因为它仍然依赖于后台使用的api.net与内核通信。

    由于目前大多数文件系统都支持Unicode,所以可能还需要检查correcly编码的Unicode、规范化等的所有规则。

    我要做的是只做一些基本检查,然后在使用路径后正确地处理异常。有关可能的规则,请参见:

        2
  •  51
  •   Matthew Flaschen    14 年前

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

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

    boolean possiblePath = pathString.IndexOfAny(Path.GetInvalidPathChars()) == -1;
    
        3
  •  8
  •   Rox    14 年前

    以下是一些您可能会用到的东西:

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

    路径参数包含无效字符、为空或仅包含空格。

        4
  •  3
  •   atamanroman    14 年前

    在尝试创建该文件之前,您不能真正确定。可能路径有效,但安全设置不允许创建文件。唯一能告诉您路径是否真的有效的实例是操作系统,那么为什么不尝试创建一个catch-the-ioexception文件,该文件指示发生了真正的错误?imho这是一个更简单的方法:假设输入是有效的,如果输入无效,就做一些事情,而不是做很多不必要的工作。

        5
  •  2
  •   Justin L.    14 年前

    你试过正则表达式吗?

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

    应该工作

        6
  •  2
  •   vCillusion    9 年前

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

    /// <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;
    }
    
        7
  •  1
  •   Ghislain Zabatio    8 年前
    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;
        }
    
        8
  •  0
  •   Jonas Stensved    14 年前

    我在regexlib.com上找到这个( http://regexlib.com/REDetails.aspx?regexp_id=345 )作者:Dmitry Borysov。

    “文件名验证程序。验证UNC(\server\share\file)和常规MS路径(c:\file)“

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

    用regex.ismatch运行它,您将得到一个bool,指示它是否有效。我认为正则表达式是可行的,因为该文件可能不存在。

        9
  •  0
  •   Jerry    12 年前

    只需在try catch语句中使用path.combine():

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

    编辑: 请注意,如果路径包含通配符(“*”和“?”),则此函数不会引发异常。因为它们可以在搜索字符串中使用。

        10
  •  0
  •   Eric Anastas    11 年前

    静态类system.io.path可以满足您的要求。