使用以下代碼,我將分別接收所有 Windows 硬碟的卷
foreach (var drive in DriveInfo.GetDrives())
{
int bb = Convert.ToInt32(drive.TotalSize / 1024 / 1024 / 1024);
}
這就是回報
100GB 500GB 2300GB
但我想收集號碼并交出 但這就是我想要的 100GB 500GB 2300GB
2900GB
uj5u.com熱心網友回復:
您可以在https://dotnetfiddle.net/27YcIp上測驗/運行此代碼
using System.Linq;
using System.IO;
using System;
Console.WriteLine(Drives.GetAllDriveSizeA());
Console.WriteLine(Drives.GetAllDriveSizeB());
Console.WriteLine(Drives.GetAllDriveSizeC());
Console.WriteLine(Drives.GetAllDriveSizeD());
Console.ReadLine();
public static class Drives
{
public static long GetAllDriveSizeA() // With Linq
{
return DriveInfo.GetDrives().Where(d => d.IsReady).Sum(d => d.TotalSize / 1024 / 1024 / 1024);
}
public static long GetAllDriveSizeB()
{
long total = 0;
foreach (DriveInfo drive in DriveInfo.GetDrives()) //With foreach loop
{
if (drive.IsReady)
{
total = drive.TotalSize / 1024 / 1024 / 1024;
}
}
return total;
}
public static long GetAllDriveSizeC()//With for loop
{
long total = 0;
DriveInfo[] drives = DriveInfo.GetDrives();
for (int i = 0; i < drives.Length; i )
{
if (drives[i].IsReady)
{
total = drives[i].TotalSize / 1024 / 1024 / 1024;
}
}
return total;
}
public static long GetAllDriveSizeD() //With List<T>.Foreach
{
long total = 0;
DriveInfo.GetDrives().ToList().ForEach(drive =>
{
if (drive.IsReady)
{
total = drive.TotalSize / 1024 / 1024 / 1024;
}
});
return total;
}
}
//DriveInfo.GetDrives() - Get Drive list.
//Where(d => d.IsReady) - filters only drives(elements) that are ready otherwise will get exception when trying to get total size.
//Sum(d => d.TotalSize / 1024 / 1024 / 1024) - Sum each element / 1024 / 1024 / 1024
//d => .... Is lambda expression (anonymous function). d is the parameter of the function and .... is the value returned by this function.
輸出我的電腦
1360
1360
1360
1360
參考
Lambda 運算式
Linq - Where
Linq - Sum
List.Foreach
uj5u.com熱心網友回復:
這樣您就可以獲得所有磁盤的位元組容量:
int byteTotalCapacity = 0;
foreach (var drive in DriveInfo.GetDrives())
{
byteTotalCapacity = drive.TotalSize;
}
如果你想要它在 GB 你必須除以 (1024*1024)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458743.html
