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

43

这可能是一个愚蠢的问题,那么问题来了:

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


警告:这并非在所有情况下都有效!仅仅因为驱动器的根目录有足够的空间并不意味着当前目录有足够的空间。同样地,根目录可能没有足够的空间,但是当前目录有足够的空间。至少Windows可以计算出当前目录中的空间,多个程序正确报告当前目录中的可用空间,即使它与根目录中的空间不匹配。我还没有研究如何实现这一点。(我考虑的情况是映射到子目录中的卷。) - Loren Pechtel
4个回答

79
FileInfo f = new FileInfo(path);    
string drive = Path.GetPathRoot(f.FullName);

这将返回"C:\"。那确实是唯一的另一种方法。


29

嗯,还有这个:

FileInfo file = new FileInfo(path);
DriveInfo drive = new DriveInfo(file.Directory.Root.FullName);

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

public static DriveInfo GetDriveInfo(this FileInfo file)
{
    return new DriveInfo(file.Directory.Root.FullName);
}

那么你可以直接这样做:

DriveInfo drive = new FileInfo(path).GetDriveInfo();

GetDriveInfo在FileInfo上似乎不存在,我只在VB中找到了它的引用,而不是C#。 - Josh
1
DriveInfo 调用 GetPathRoot(),所以如果只想要驱动器字母,这是额外的开销。另一方面,很酷;直到现在我都不知道 DriveInfo 的存在。 - Still.Tony

-3
您可以使用以下代码获取系统中的所有驱动器:
foreach (DriveInfo objDrive in DriveInfo.GetDrives())
    {
        Response.Write("</br>Drive Type : " + objDrive.Name);
        Response.Write("</br>Drive Type : " + objDrive.DriveType.ToString());
        Response.Write("</br>Available Free Space : " + objDrive.AvailableFreeSpace.ToString() + "(bytes)");
        Response.Write("</br>Drive Format : " + objDrive.DriveFormat);
        Response.Write("</br>Total Free Space : " + objDrive.TotalFreeSpace.ToString() + "(bytes)");
        Response.Write("</br>Total Size : " + objDrive.TotalSize.ToString() + "(bytes)");
        Response.Write("</br>Volume Label : " + objDrive.VolumeLabel);
        Response.Write("</br></br>");

    }

3
将这个回答回滚以包含一位版主从您的帖子中删除的垃圾链接是不恰当的。 - Andrew Barber

-3

对于一些字符串解析没什么问题 :-)

FullPath.Substring(0,1);

23
这对路径做出了不安全的假设。请考虑实际上是UNC路径名的情况,形式为\machinename\share\path\filename.txt。 - Steven Sudit
12
当涉及到文件系统路径时,一切都需要进行“一点字符串解析”,因为总会有不完美的地方。 - turbo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接