DriveInfo[] drives = DriveInfo.GetDrives();
for (int i = 0; i < drives.Length; i++)
{
if (drives[i].IsReady)
{
Console.WriteLine("Drive {0} - Has free space of {1} GB",drives[i].ToString(),(drives[i].TotalFreeSpace/1024/1024/1024).ToString("N2"));
}
}
输出:
Drive C:\ - Has free space of 70,00 GB
Drive D:\ - Has free space of 31,00 GB
Drive E:\ - Has free space of 7,00 GB
Drive F:\ - Has free space of 137,00 GB
所有结果都是00,但我需要显示实际尺寸。那么哪种格式合适?
答案 0 :(得分:4)
格式字符串与它没有任何关系。您的整数运算正在丢弃任何余数。
3920139012 / 1024 / 1024 / 1024 // 3
使用m
后缀指定小数,如下所示:
3920139012 / 1024m / 1024m / 1024m // 3.6509139575064182281494140625
可替换地:
3920139012 / Math.Pow(1024, 3) // 3.65091395750642
这可能会更清楚一点:
var gb = Math.Pow(1024, 3);
foreach(var drive in DriveInfo.GetDrives())
{
if(drive.IsReady)
{
Console.WriteLine("Drive {0} - Has free space of {1:n2} GB",
drive.Name,
drive.TotalFreeSpace / gb);
}
}
答案 1 :(得分:4)
因为您正在执行整数除法,它会截断小数余数。改为使用浮点除法:
drives[i].TotalFreeSpace/1024.0/1024.0/1024.0
或
drives[i].TotalFreeSpace / (1024.0 * 1024.0 * 1024.0)