[英]How do I retrieve disk information in C#?
我想使用 C# 访问有关我计算机上的逻辑驱动器的信息。 我应该如何做到这一点? 谢谢!
对于大多数信息,您可以使用DriveInfo类。
using System;
using System.IO;
class Info {
public static void Main() {
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives) {
//There are more attributes you can use.
//Check the MSDN link for a complete example.
Console.WriteLine(drive.Name);
if (drive.IsReady) Console.WriteLine(drive.TotalSize);
}
}
}
如果您想在本地机器上获取单个/特定驱动器的信息。 您可以使用DriveInfo类执行以下操作:
//C Drive Path, this is useful when you are about to find a Drive root from a Location Path.
string path = "C:\\Windows";
//Find its root directory i.e "C:\\"
string rootDir = Directory.GetDirectoryRoot(path);
//Get all information of Drive i.e C
DriveInfo driveInfo = new DriveInfo(rootDir); //you can pass Drive path here e.g DriveInfo("C:\\")
long availableFreeSpace = driveInfo.AvailableFreeSpace;
string driveFormat = driveInfo.DriveFormat;
string name = driveInfo.Name;
long totalSize = driveInfo.TotalSize;
没有驱动器号的挂载卷呢?
foreach( ManagementObject volume in
new ManagementObjectSearcher("Select * from Win32_Volume" ).Get())
{
if( volume["FreeSpace"] != null )
{
Console.WriteLine("{0} = {1} out of {2}",
volume["Name"],
ulong.Parse(volume["FreeSpace"].ToString()).ToString("#,##0"),
ulong.Parse(volume["Capacity"].ToString()).ToString("#,##0"));
}
}
使用 System.IO.DriveInfo 类http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx
检查DriveInfo类,看看它是否包含您需要的所有信息。
在 ASP .NET Core 3.1 中,如果您想获得在 windows 和 linux 上都能运行的代码,您可以按如下方式获取驱动器:
var drives = DriveInfo
.GetDrives()
.Where(d => d.DriveType == DriveType.Fixed)
.Where(d => d.IsReady
.ToArray();
如果您不同时应用这两个 wheres,那么如果您在 linux 中运行代码(例如“/dev”、“/sys”、“/etc/hosts”等),您将获得许多驱动器。
这在开发应用程序以在 Linux Docker 容器中工作时特别有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.