检查路径是否为UNC路径最简单的方法当然是检查完整路径中的第一个字符是否为字母或反斜杠。这是一种好的解决方案吗?还是可能存在问题?
我的具体问题是:如果路径中有驱动器号,我想创建一个System.IO.DriveInfo对象。
试试这个扩展方法:
public static bool IsUncPath(this string path)
{
return Uri.TryCreate(path, UriKind.Absolute, out Uri uri) && uri.IsUnc;
}
由于第一和第二个位置没有两个反斜杠的路径在定义上不是UNC路径,因此这是一种确定路径类型的安全方式。
第一个位置有驱动器盘符(如c:)的路径是根本地路径。
没有这些内容的路径(如myfolder\blah)是相对本地路径。这也包括只有一个斜杠的路径(\myfolder\blah)。
C
语言的。@ShengJiang蒋晟,在 .NET 中我们有 System.IO.Path.DirectorySeparatorChar
。 - Nicolas最准确的方法是使用一些来自 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使用纯托管代码给出了最佳答案。
我发现的一个技巧是使用 dInfo.FullName.StartsWith(String.Empty.PadLeft(2, IO.Path.DirectorySeparatorChar))
这段代码,其中dInfo是一个DirectoryInfo对象 - 如果这个检查返回True,则它是一个UNC路径,否则它是一个本地路径。
.StartsWith(new string(Path.DirectorySeparatorChar, 2))
。 - jnm2public 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;
}
DriveInfo
。
DirectoryInfo.DriveType == DriveType.Network
而不是Uri.TryCreate
有什么原因吗? - larsmoa