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

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

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

检查DirectoryInfo.Parent是否为null

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

你也可以使用DirectoryInfo.Root获取root;

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

确定目录是否是已装入的文件夹

一种方法是查看GetVolumeNameForVolumeMountPoint成功。

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

试试这个 :

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

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

  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); } 

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