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

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?

0

2 Answers 2

4

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.