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

时间:2008-12-16 01:39:15

标签: c# file-io

这看起来像是一个愚蠢的问题,所以这里是:

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

4 个答案:

答案 0 :(得分:45)

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

这将返回“C:\”。这是唯一的另一种方式。

答案 1 :(得分:23)

嗯,还有这个:

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();

答案 2 :(得分:0)

小字符串解析没什么问题: - )

FullPath.SubString(0,1);

答案 3 :(得分:-1)

您可以使用以下代码获取系统中的所有驱动器:

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>");

    }