C# 从路径字符串或 FileInfo 获取驱动器号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/370267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the drive letter from a path string or FileInfo
提问by maxfridbe
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.FullPath 字符串然后使用 DriveInfo("c") 等查看是否有足够的空间来写入此文件。有没有办法从 FileInfo 获取驱动器号?
采纳答案by BFree
FileInfo f = new FileInfo(path);
string drive = Path.GetPathRoot(f.FullName);
This will return "C:\". That's really the only other way.
这将返回“C:\”。这真的是唯一的其他方式。
回答by Joel Martinez
Nothing wrong with a little string parsing :-)
一点字符串解析没有错:-)
FullPath.Substring(0,1);
回答by Dan Tao
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();
回答by Jayesh Sorathia
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>");
}