[英]How do I retrieve disk information in C#?
I would like to access information on the logical drives on my computer using C#.我想使用 C# 访问有关我计算机上的逻辑驱动器的信息。 How should I accomplish this?
我应该如何做到这一点? Thanks!
谢谢!
For most information, you can use the DriveInfo class.对于大多数信息,您可以使用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);
}
}
}
If you want to get information for single/specific drive at your local machine.如果您想在本地机器上获取单个/特定驱动器的信息。 You can do it as follow using DriveInfo class:
您可以使用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;
What about mounted volumes, where you have no drive letter?没有驱动器号的挂载卷呢?
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类,看看它是否包含您需要的所有信息。
In ASP .NET Core 3.1, if you want to get code that works both on windows and on linux, you can get your drives as follows:在 ASP .NET Core 3.1 中,如果您想获得在 windows 和 linux 上都能运行的代码,您可以按如下方式获取驱动器:
var drives = DriveInfo
.GetDrives()
.Where(d => d.DriveType == DriveType.Fixed)
.Where(d => d.IsReady
.ToArray();
If you don't apply both wheres, you are going to get many drives if you run the code in linux (eg "/dev", "/sys", "/etc/hosts", etc.).如果您不同时应用这两个 wheres,那么如果您在 linux 中运行代码(例如“/dev”、“/sys”、“/etc/hosts”等),您将获得许多驱动器。
This is specially useful when developing an app to work in a Linux Docker container.这在开发应用程序以在 Linux Docker 容器中工作时特别有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.