2014-01-21 56 views
1
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")); 
    } 
} 

輸出:帶十進制格式的C#string.format。

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但是我需要顯示實際尺寸。那麼哪種格式適合?

回答

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); 
    } 
} 
4

Becasue您AR e做整數除法它截斷了十進制餘數。使用浮點除法來代替:

drives[i].TotalFreeSpace/1024.0/1024.0/1024.0 

drives[i].TotalFreeSpace/(1024.0 * 1024.0 * 1024.0)