34

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

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

4

5 回答 5

36

检查 DirectoryInfo.Parent 是否为空

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

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

于 2011-02-18T23:16:55.537 回答
9

试试这个

if (Path.GetPathRoot(location) == location) {...}
于 2011-02-18T23:22:02.100 回答
5

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

判断目录是否为挂载文件夹

一种方法是查看是否GetVolumeNameForVolumeMountPoint成功。

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

于 2011-02-19T00:22:13.467 回答
3

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

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

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

于 2014-10-16T09:02:22.887 回答
1

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

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

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

于 2011-02-24T03:35:03.343 回答