我如何知道给定目录是否是根驱动器?
(除了检查其路径是否等于“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);
}
这实际上检查给定路径是否代表当前系统的逻辑驱动器之一。