检查字符串是否是有效的Windows目录(文件夹)路径

Pud*_*duk 76 c# windows filesystems directory validation

我试图确定用户输入的字符串是否有效表示文件夹的路径.有效,我的意思是格式正确.

在我的应用程序中,该文件夹代表安装目标.提供的文件夹路径有效的,我想,以确定是否该文件夹存在,并创建它,如果它没有.

我目前正在使用IO.Directory.Exists( String path ).我发现这很好用,除非用户没有正确格式化字符串.发生这种情况时,此方法将返回false,表示该文件夹不存在.但这是一个问题,因为我之后将无法创建该文件夹.

从我的谷歌搜索我发现一个建议使用正则表达式来检查格式是否正确.我没有正则表达式的经验,我想知道这是否是一种可行的方法.这是我发现的:

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

将正则表达式测试结合起来Directory.Exists(),给我一个足够好的方法来检查路径是否有效以及它是否存在?我知道这会因操作系统和其他因素而异,但该程序仅针对Windows用户.

SLa*_*aks 106

打电话Path.GetFullPath; 如果路径无效,它将抛出异常.

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

  • @Slaks这个太老了,不能发表评论,但我还是想在这里留一个,因为我给你的投票是-1.Path.GetFullPath()似乎工作正常,但如果路径是:"Z:\\\\\\\\ Hi \\\\\\ There",它不是有效的绝对路径,而是Path.GetFullPath (...)给出结果:Z:\ Hi \那里没有异常.我不得不通过比较GetFullPath()返回的字符串和原始字符串来改变它:private bool IsPathValid(string path){try {string fullPath = Path.GetFullPath(path); return fullPath == path; } catch {return false;}} (8认同)
  • Path.GetFullPath("con.txt")是有效的文件名. (5认同)
  • @KingKing来自[这个Linux答案](http://unix.stackexchange.com/a/1919)在unix.stackexchange.com上:*"允许多个斜杠,相当于一个斜杠......"*我观察到了在Windows上也是如此(尽管UNC路径中的前导斜杠可能会有不同的处理方式).为了证明这一点,在命令提示符下,尝试:`cd C:\\\\\\\ Windows \\\\\\\ System32`.对于Windows,我找不到记录此行为的权威来源,但当然会欢迎指向一个的指针. (4认同)
  • 这不会捕获所有无效路径;例如,它没有发现 `"c:\e:\g:\"` 无效。 (3认同)
  • 谢谢SLaks.我看过很多重复,并且不止一次地进行了很多谷歌搜索,但这是我第一次看到这个特定问题的答案. (2认同)

Sco*_*ith 18

我实际上不同意SLaks.那个解决方案对我不起作用.异常没有按预期发生.但是这段代码对我有用:

if(System.IO.Directory.Exists(path))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 有效路径不一定是存在的目录......这正是这里提出的问题 (51认同)
  • 问题与路径字符串的验证有关,路径字符串可能不存在。 (2认同)

vCi*_*ion 11

Path.GetFullPath仅提供以下异常

ArgumentException路径是零长度字符串,仅包含空格,或包含GetInvalidPathChars中定义的一个或多个无效字符. - 或 - 系统无法检索绝对路径.

SecurityException调用方没有所需的权限.

ArgumentNullException路径为null.

NotSupportedException路径包含冒号(":"),该冒号不是卷标识符的一部分(例如,"c:\").

PathTooLongException指定的路径,文件名或两者都超过系统定义的最大长度.例如,在基于Windows的平台上,路径必须少于248个字符,文件名必须少于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;
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*dRR 9

这是一个利用Path.GetFullPath的解决方案,正如@SLaks答案中所建议的那样.

在此,我这里有包括代码,请注意,IsValidPath(string path)被设计成调用者担心异常处理.

您可能还会发现,TryGetFullPath(...)当您希望安全地尝试获取绝对路径时,它调用的方法也有其自身的优点.

/// <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;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

使用此代码

string DirectoryName = "Sample Name For Directory Or File";
Path.GetInvalidFileNameChars().Where(x => DirectoryName.Contains(x)).Count() > 0 || DirectoryName == "con"
Run Code Online (Sandbox Code Playgroud)

  • 略微缩短的代码完成同样的事情:`Path.GetInvalidFileNameChars().Any(DirectoryName.Contains)|| DirectoryName =="con"` (4认同)
  • @nawfal确实。从MSDN上的[命名文件,路径和命名空间](https://msdn.microsoft.com/zh-cn/library/windows/desktop/aa365247(v = vs.85).aspx):*“请勿使用文件名的以下保留名称:CON,PRN,AUX,NUL,COM1,COM2,COM3,COM4,COM5,COM6,COM7,COM8,COM9,LPT1,LPT2,LPT3,LPT4,LPT5,LPT6,LPT7 ,LPT8和LPT9。也请避免在这些名称后立即加上扩展名;例如,不建议使用NUL.txt。有关更多信息,请参见[命名空间](https://msdn.microsoft.com/zh-cn/library /windows/desktop/aa365247(v=vs.85).aspx#namespaces)。"* (2认同)

SNa*_*Nag 6

更简单的独立于操作系统的解决方案:

继续尝试创建实际的目录;如果存在问题或名称无效,操作系统将自动抱怨并且代码将抛出。

public static class PathHelper
{
    public static void ValidatePath(string path)
    {
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path).Delete();
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

try
{
    PathHelper.ValidatePath(path);
}
catch(Exception e)
{
    // handle exception
}
Run Code Online (Sandbox Code Playgroud)

Directory.CreateDirectory()会自动抛出以下所有情况:

System.IO.IOException:
路径指定的目录是一个文件。- 或 - 网络名称未知。

System.UnauthorizedAccessException:
调用者没有所需的权限。

System.ArgumentException:
路径是零长度字符串,仅包含空格,或者包含一个或多个无效字符。您可以使用 System.IO.Path.GetInvalidPathChars 方法查询无效字符。- 或 - 路径以冒号字符 (:) 为前缀,或仅包含冒号字符 (:)。

System.ArgumentNullException:
路径为空。

System.IO.PathTooLongException:
指定的路径、文件名或两者都超出了系统定义的最大长度。

System.IO.DirectoryNotFoundException:
指定的路径无效(例如,位于未映射的驱动器上)。

System.NotSupportedException:
路径包含不属于驱动器标签(“C:”)的冒号字符(:)。


Ale*_*lig 5

    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;
    }
Run Code Online (Sandbox Code Playgroud)