繁体   English   中英

C# 如何知道给定的路径是否代表根驱动器?

[英]C# How to know if a given path represents a root drive?

如何知道给定目录是否是根驱动器?

(除了检查它的路径是否等于“A:”、“B:”、“C:”等)

检查 DirectoryInfo.Parent 是否为空

DirectoryInfo d = new DirectoryInfo("");
if(d.Parent == null) { IsRoot = true; }

您还可以使用 DirectoryInfo.Root 获取根目录;

试试这个

if (Path.GetPathRoot(location) == location) {...}

这比检查 Parent 属性要复杂得多。

确定目录是否为挂载文件夹

一种方法是查看GetVolumeNameForVolumeMountPoint成功。

当然,这不适用于网络路径,远程确定网络驱动器是否代表分区的根目录可能是不可能的。

另外这是我发现的另一种方式:

 public static bool IsLogicalDrive(string path)
 {
     return (new DirectoryInfo(path).FullName == new DirectoryInfo(path).Root.FullName);
 }

如果此函数返回 true,则表示给定路径表示根驱动器!

这是我发现的另一种方法:

public static bool IsLogicalDrive(string path)
{
    return Directory.GetLogicalDrives().Contains(path);
}

这个实际上检查给定的路径是否代表当前系统的逻辑驱动器之一。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM