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

asm*_*smo 28 c# directory drive root

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

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

Dus*_*vis 33

检查DirectoryInfo.Parent是否为null

DirectoryInfo d = new DirectoryInfo("");
if(d.Parent == null) { IsRoot = true; }
Run Code Online (Sandbox Code Playgroud)

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


Bra*_*don 6

试试这个:

if (Path.GetPathRoot(location) == location) {...}
Run Code Online (Sandbox Code Playgroud)

  • @Titan:如果获取root返回相同的字符串,那么它就是root.它可能不是最好的方法,但它是有效的. (3认同)
  • @DustinDavis效率远远低于什么?如果你分配一个`DirectoryInfo`你现在必须要GC一个`DirectoryInfo`而不是一个字符串,`GetVolumeNameForVolumeMountPoint`使用interop并且还有开销,`Directory.GetLogicalDrives()`返回一个字符串数组...... (3认同)

Ben*_*igt 6

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

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

一种方法是看是否GetVolumeNameForVolumeMountPoint成功.

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