使用 DriveInfo 就可以直接取得磁碟上的資訊,範例程式碼如下:
範例輸出:
參考資料:
Microsoft.Learn - DriveInfo Class
// 取得所有可用的硬碟
DriveInfo[] drives = DriveInfo.GetDrives();
// 逐一顯示硬碟的資訊
foreach (DriveInfo drive in drives)
{
Console.WriteLine($"硬碟名稱:{drive.Name}");
Console.WriteLine($"磁碟類型:{drive.DriveType}");
Console.WriteLine($"是否就緒:{drive.IsReady}");
if (drive.IsReady)
{
Console.WriteLine($"檔案系統格式:{drive.DriveFormat}");
Console.WriteLine($"磁碟根目錄 : {drive.RootDirectory}");
Console.WriteLine($"磁碟區標籤:{drive.VolumeLabel}");
Console.WriteLine($"總容量(bytes) : {drive.TotalSize}");
Console.WriteLine($"可用空間(bytes) : {drive.TotalFreeSpace}");
Console.WriteLine($"可用空間(bytes) : {drive.AvailableFreeSpace}");
// 轉換為 GB
double totalSpaceGB = drive.TotalSize / (1024 * 1024 * 1024.0);
double freeSpaceGB = drive.AvailableFreeSpace / (1024 * 1024 * 1024.0);
Console.WriteLine($"總容量:{totalSpaceGB:F2} GB");
Console.WriteLine($"可用空間:{freeSpaceGB:F2} GB");
}
else
{
Console.WriteLine("此硬碟未就緒,無法取得容量資訊。");
}
}
範例輸出:
硬碟名稱:C:\
磁碟類型:Fixed
是否就緒:True
檔案系統格式:NTFS
磁碟根目錄 : C:\
磁碟區標籤:
總容量(bytes) : 1999558930432
可用空間(bytes) : 942798548992
可用空間(bytes) : 942798548992
總容量:1862.23 GB
可用空間:878.05 GB
參考資料:
Microsoft.Learn - DriveInfo Class
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com