Get the drive letter from a path string or FileInfo

佐手、 提交于 2019-12-30 01:40:08

问题


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?


回答1:


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

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




回答2:


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



回答3:


Nothing wrong with a little string parsing :-)

FullPath.Substring(0,1);



回答4:


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

    }


来源:https://stackoverflow.com/questions/370267/get-the-drive-letter-from-a-path-string-or-fileinfo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!