问题
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