检查路径是否为UNC路径的最简单方法当然是检查完整路径中的第一个字符是字母还是反斜杠.这是一个很好的解决方案还是会出现问题?
我的具体问题是,如果路径中有驱动器号,我想创建一个System.IO.DriveInfo对象.
Jar*_*Par 16
试试这个扩展方法
public static bool IsUncDrive(this DriveInfo info) {
Uri uri = null;
if ( !Uri.TryCreate(info.Name, UriKind.Absolute, out uri) ) {
return false;
}
return uri.IsUnc;
}
Run Code Online (Sandbox Code Playgroud)
The*_*urf 15
由于在第一和第二位置没有两个反斜杠的路径通过定义而不是UNC路径,因此这是进行该确定的安全方式.
第一个位置(c :)中带有驱动器号的路径是带根的本地路径.
没有这些东西的路径(myfolder\blah)是一个相对的本地路径.这包括只有一个斜杠的路径(\ myfolder\blah).
Sco*_*man 13
最准确的方法是使用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);
Run Code Online (Sandbox Code Playgroud)
然后你会这样称呼它:
/// <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);
}
Run Code Online (Sandbox Code Playgroud)
@JaredPar使用纯托管代码获得最佳答案.
这是我的版本:
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;
}
Run Code Online (Sandbox Code Playgroud)
与@JaredPars版本相比,此版本的优势在于它支持任何路径,而不仅限于DriveInfo。
小智 5
我发现的一个技巧是使用dInfo.FullName.StartsWith(String.Empty.PadLeft(2, IO.Path.DirectorySeparatorChar))dInfo是DirectoryInfo对象的地方 - 如果该检查返回True则它是UNC路径,否则它是本地路径
| 归档时间: |
|
| 查看次数: |
24031 次 |
| 最近记录: |