从路径字符串或FileInfo获取驱动器号

max*_*dbe 22 c# file-io

这似乎是一个愚蠢的问题,所以这里是:

除了解析驱动器号的FileInfo.FullPath字符串之外,然后使用DriveInfo("c")等来查看是否有足够的空间来写入此文件.有没有办法从FileInfo获取驱动器号?

BFr*_*ree 48

FileInfo f = new FileInfo(path);    
string drive = Path.GetPathRoot(f.FullName);
Run Code Online (Sandbox Code Playgroud)

这将返回"C:\".这真的是唯一的另一种方式.


Dan*_*Tao 23

嗯,还有这个:

FileInfo file = new FileInfo(path);
DriveInfo drive = new DriveInfo(file.Directory.Root.FullName);
Run Code Online (Sandbox Code Playgroud)

嘿,为什么不是扩展方法呢?

public static DriveInfo GetDriveInfo(this FileInfo file)
{
    return new DriveInfo(file.Directory.Root.FullName);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

DriveInfo drive = new FileInfo(path).GetDriveInfo();
Run Code Online (Sandbox Code Playgroud)