简体   繁体   中英

Get the drive letter from a path string or FileInfo

This may seem like a stupid question, so here goes:

Other than parsing the string of FileInfo.FullPath for the drive letter to then use DriveInfo("c") etc to see if there is enough space to write this file. Is there a way to get the drive letter from FileInfo?

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

This will return "C:\\". That's really the only other way.

Well, there's also this:

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

And hey, why not an extension method?

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

Then you could just do:

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

一个小字符串解析没有错:-)

FullPath.SubString(0,1);

You can get all drive in system using this code :

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM