【发布时间】:2011-06-30 04:10:15
【问题描述】:
我如何知道给定目录是否是根驱动器?
(除了检查其路径是否等于“A:”、“B:”、“C:”等)
【问题讨论】:
-
您想知道给定目录是否是某个分区的根目录,对吧?
-
是的,这就是我要求的。
我如何知道给定目录是否是根驱动器?
(除了检查其路径是否等于“A:”、“B:”、“C:”等)
【问题讨论】:
检查 DirectoryInfo.Parent 是否为空
DirectoryInfo d = new DirectoryInfo("");
if(d.Parent == null) { IsRoot = true; }
您也可以通过 DirectoryInfo.Root 获取根目录;
【讨论】:
试试this:
if (Path.GetPathRoot(location) == location) {...}
【讨论】:
DirectoryInfo 你现在必须 GC 一个 DirectoryInfo 而不是一个字符串,GetVolumeNameForVolumeMountPoint 使用互操作并且也会有开销,Directory.GetLogicalDrives() 返回一个字符串数组...
这比检查 Parent 属性要复杂得多。
Determining Whether a Directory Is a Mounted Folder
一种方法是查看GetVolumeNameForVolumeMountPoint 是否成功。
当然这不适用于网络路径,远程确定网络驱动器是否代表分区的根目录可能是不可能的。
【讨论】:
DirectoryInfo.Parent 会告诉你它是一个子目录,而实际上它是另一个分区的根目录。没有托管函数来测试特定目录是否是其分区的根目录,这就是我建议使用本机 Win32 函数的原因。
还有我发现的另一种方法:
public static bool IsLogicalDrive(string path)
{
return (new DirectoryInfo(path).FullName == new DirectoryInfo(path).Root.FullName);
}
如果此函数返回true,则表示给定路径代表一个根驱动器!
【讨论】:
Path.GetPathRoot() 在某些情况下可能是更方便的选择,但它找不到相对路径的根。 docs.microsoft.com/en-us/dotnet/api/… 另外,由于我们使用的是字符串比较,我们希望确保双方获得相同的格式。
new DirectoryInfo(path).Root.FullName 也不确定是一致的,因为它可能返回驱动器号的大写或小写版本。最好也进行字符串转换。
这是我找到的另一种方法:
public static bool IsLogicalDrive(string path)
{
return Directory.GetLogicalDrives().Contains(path);
}
这个实际上检查给定路径是否代表当前系统的逻辑驱动器之一。
【讨论】:
Directory.GetLogicalDrives 返回一个string[]。 System.Array 实现 System.Collections.IList,但它为 Contains 提供了显式接口实现: ((.NET 3.5+: msdn.microsoft.com/en-us/library/bb336401(v=vs.110).aspx )) ((.NET 2, 3: msdn.microsoft.com/en-US/library/… )) ((.NET 1.1: @ 987654324@ )) 在调用 Contains 之前,必须将数组转换为 IList。