27

检查路径是否为 UNC 路径的最简单方法当然是检查完整路径中的第一个字符是字母还是反斜杠。这是一个好的解决方案还是可能有问题?

我的具体问题是,如果路径中有驱动器号,我想创建一个 System.IO.DriveInfo 对象。

4

5 回答 5

23

试试这个扩展方法:

public static bool IsUncPath(this string path)
{
    return Uri.TryCreate(path, UriKind.Absolute, out Uri uri) && uri.IsUnc;
}
于 2009-02-06T15:46:51.663 回答
20

由于根据定义,在第一个和第二个位置没有两个反斜杠的路径不是 UNC 路径,因此这是一种安全的确定方式。

第一个位置 (c:) 带有驱动器号的路径是根本地路径。

没有这些东西的路径 (myfolder\blah) 是相对本地路径。这包括只有一个斜杠 (\myfolder\blah) 的路径。

于 2009-02-06T15:42:14.620 回答
14

最准确的方法是使用 shlwapi.dll 中的一些互操作代码

[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
internal static extern bool PathIsUNC([MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath);

然后你会这样称呼它:

    /// <summary>
    /// Determines if the string is a valid Universal Naming Convention (UNC)
    /// for a server and share path.
    /// </summary>
    /// <param name="path">The path to be tested.</param>
    /// <returns><see langword="true"/> if the path is a valid UNC path; 
    /// otherwise, <see langword="false"/>.</returns>
    public static bool IsUncPath(string path)
    {
        return PathIsUNC(path);
    }

@JaredPar 使用纯托管代码的最佳答案。

于 2009-02-06T15:46:13.333 回答
5

这是我的版本:

public static bool IsUnc(string path)
{
    string root = Path.GetPathRoot(path);

    // Check if root starts with "\\", clearly an UNC
    if (root.StartsWith(@"\\"))
    return true;

    // Check if the drive is a network drive
    DriveInfo drive = new DriveInfo(root);
    if (drive.DriveType == DriveType.Network)
    return true;

    return false;
}

此版本相对于@JaredPars 版本的优势在于它支持任何路径,而不仅仅是DriveInfo.

于 2013-09-19T08:17:56.560 回答
5

我发现的一个技巧是使用dInfo.FullName.StartsWith(String.Empty.PadLeft(2, IO.Path.DirectorySeparatorChar))where dInfo 是 DirectoryInfo 对象 - 如果该检查返回 True 那么它是一个 UNC 路径,否则它是一个本地路径

于 2013-09-20T01:11:35.373 回答