如何正确地检查路径是UNC路径还是本地路径?

30

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

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

5个回答

29

试试这个扩展方法:

public static bool IsUncPath(this string path)
{
    return Uri.TryCreate(path, UriKind.Absolute, out Uri uri) && uri.IsUnc;
}

5
DriveInfo对象不能用于UNC路径。但如果我将其更改为DirectoryInfo的扩展,并使用FullName而不是Name,它似乎可以正常工作。 - David Eliason
1
使用 DirectoryInfo.DriveType == DriveType.Network 而不是 Uri.TryCreate 有什么原因吗? - larsmoa
1
不使用DirectoryInfo.DriveType的原因是DriveInfo中存在这样一个属性,而DriveInfo无法使用UNC路径进行初始化。 - Eugenio Miró

20

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

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

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


你应该至少检查 "\" 是否作为路径的起始符,因为 "\this\is\not\a\unc\path"(虽然这不是一个特别好的路径,但它并不是 UNC)。 - Michael Burr
1
本地化系统中路径分隔符不同怎么办?例如,在日本系统中使用¥。 - Sheng Jiang 蒋晟
1
请参考以下问题的答案:https://dev59.com/ZGw05IYBdhLWcg3wUAM0 - TheSmurf
1
映射的目录和符号链接也可以指向UNC路径,因此可能不是本地路径。 - Edd
@TheSmurf,你所提到的问题是关于 C 语言的。@ShengJiang蒋晟,在 .NET 中我们有 System.IO.Path.DirectorySeparatorChar - Nicolas

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使用纯托管代码给出了最佳答案。


5

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


6
或者.StartsWith(new string(Path.DirectorySeparatorChar, 2)) - jnm2

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接