检查路径是否为UNC路径的最简单方法当然是检查完整路径中的第一个字符是字母还是反斜线。这是一个好的解决方案,还是可能有问题?
我的具体问题是,如果路径中有驱动器号,我想创建一个System.IO.DriveInfo对象。
由于在第一和第二位置上没有两个反斜线的路径不是UNC路径,所以这是确定的安全方法。
驱动器号在第一个位置(c :)的路径是有根的本地路径。
没有任何一项(myfolder \ blah)的路径是相对本地路径。这包括仅包含一个斜杠(\ myfolder \ blah)的路径。
尝试此扩展方法:
public static bool IsUncPath(this string path)
{
return Uri.TryCreate(path, UriKind.Absolute, out Uri uri) && uri.IsUnc;
}
最准确的方法是使用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使用purely managed code可获得最佳答案。
这是我的版本:
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
。
我发现的一个技巧是使用dInfo.FullName.StartsWith(String.Empty.PadLeft(2, IO.Path.DirectorySeparatorChar))
,其中dInfo是DirectoryInfo对象-如果该检查返回True,则它是UNC路径,否则是本地路径
也许此答案对想要验证仅UNC服务器+共享+子目录的人很有帮助,例如,网络存储库的路径,例如
\\Server1\Share1
\\Server2\Share22\Dir1\Dir2
\\Server3
使用以下正则表达式:
^\\\\([A-Za-z0-9_\-]{1,32}[/\\]){0,10}[A-Za-z0-9_\-]{1,32}$
32
(2次)>>10
[A-Za-z0-9_\-]
(2次)我已经成功测试了它。享受!