.net 检查路径是UNC路径还是本地路径的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/520753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 11:12:38  来源:igfitidea点击:

What is the correct way to check if a path is an UNC path or a local path?

.netpathunc

提问by David Eliason

The easiest way to check if a path is an UNC path is of course to check if the first character in the full path is a letter or backslash. Is this a good solution or could there be problems with it?

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

My specific problem is that I want to create an System.IO.DriveInfo-object if there is a drive letter in the path.

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

采纳答案by TheSmurf

Since a path without two backslashes in the first and second positions is, by definiton, not a UNC path, this is a safe way to make this determination.

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

A path with a drive letter in the first position (c:) is a rooted local path.

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

A path without either of this things (myfolder\blah) is a relative local path. This includes a path with only a single slash (\myfolder\blah).

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

回答by JaredPar

Try this extension method:

试试这个扩展方法:

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

回答by Scott Dorman

The most accurate approach is going to be using some interop code from the shlwapi.dll

最准确的方法是使用 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);

You would then call it like this:

然后你会这样称呼它:

    /// <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 has the best answer using purely managed code.

@JaredPar 使用纯托管代码给出了最佳答案。

回答by larsmoa

This is my version:

这是我的版本:

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;
}

The advantage of this version over @JaredPars version is that this supports any path, not just DriveInfo.

这个版本比@JaredPars 版本的优势在于它支持任何路径,而不仅仅是DriveInfo.

回答by DC Bane

One trick I've found is to use dInfo.FullName.StartsWith(String.Empty.PadLeft(2, IO.Path.DirectorySeparatorChar))where dInfo is a DirectoryInfo object - if that check returns True then it's a UNC path, otherwise it's a local path

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

回答by miroxlav

Maybe this answer can be helpful to someone who wants to validate only UNC server + share + subdirectories, for example path to network repository like

也许这个答案对只想验证UNC 服务器 + 共享 + 子目录的人有帮助,例如网络存储库的路径

  • \\Server1\Share1
  • \\Server2\Share22\Dir1\Dir2
  • \\Server3
  • \\Server1\Share1
  • \\Server2\Share22\Dir1\Dir2
  • \\Server3

Use the following regex:

使用以下正则表达式:

^\\([A-Za-z0-9_\-]{1,32}[/\]){0,10}[A-Za-z0-9_\-]{1,32}$
  • replace 32(2 times) with maximum allowed length of server/directory name
  • replace 10with maximum allowed path depth (maximum count of directories)
  • extend [A-Za-z0-9_\-](2 times) if you are missing some character allowed in server/directory name
  • 32服务器/目录名称的最大允许长度替换(2 次)
  • 替换10为最大允许路径深度(最大目录数)
  • [A-Za-z0-9_\-]如果您缺少服务器/目录名称中允许的某些字符,请扩展(2 次)

I've successfully tested it. Enjoy!

我已经成功测试过了。享受!