Question

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

Output:

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

All end up with ,00 but I need to show real size. So which format is suitable?

Was it helpful?

Solution

The format string doesn't have anything to do with it. Your integer operations are discarding any remainder.

3920139012 / 1024 / 1024  / 1024 // 3

Specify decimals using the m suffix like so:

3920139012 / 1024m / 1024m / 1024m // 3.6509139575064182281494140625

Alternatively:

3920139012 / Math.Pow(1024, 3) // 3.65091395750642

This might be a little more clear:

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

OTHER TIPS

Becasue you are doing integer division which truncates decimal remainders. Use floating-point division instead:

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

or

drives[i].TotalFreeSpace / (1024.0 * 1024.0 * 1024.0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top