[英]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.