Question

So we all know that the following code will return a long:

DriveInfo myDrive = new DriveInfo("C:\\");
long size = myDrive.TotalSize;
Console.WriteLine("Drive Size is: {0}", size);

The output will be something like this:

Drive Size is: 114203439104

So I think this means that the drive has a total size of around 114 GigaBytes.

However, I want to get this into the following format:

114.2 MB

Is there a really quick and easy way of doing this?

Thanks in advance.

Was it helpful?

Solution

I think that is 114 GB but hey. Anyway, I would write a helper function for this. Something like...

public string GetSize(long size)
{
   string postfix = "Bytes";
   long result = size;
   if(size >= 1073741824)//more than 1 GB
   {
      result = size / 1073741824;
      postfix = "GB";
   }
   else if(size >= 1048576)//more that 1 MB
   {
      result = size / 1048576;
      postfix = "MB";
   }
   else if(size >= 1024)//more that 1 KB
   {
      result = size / 1024;
      postfix = "KB";
   }

   return result.ToString("F1") + " " + postfix;
}

EDIT: As pointed out, I had complete forgot to deal with the size (code amended)

OTHER TIPS

This is the snippet i'm using:

    public static string FormatBytesToHumanReadable(long bytes)
    {
        if (bytes > 1073741824)
            return Math.Ceiling(bytes / 1073741824M).ToString("#,### GB");
        else if (bytes > 1048576)
            return Math.Ceiling(bytes / 1048576M).ToString("#,### MB");
        else if (bytes >= 1) 
            return Math.Ceiling(bytes / 1024M).ToString("#,### KB");
        else if (bytes < 0)
            return "";
        else
            return bytes.ToString("#,### B");
    }

Yes. Repeated division by 1024.

var kb = size/1024;
var mb = kb/1024;

I just want to add, that if you're talking about size of drive and not about size of something else, be aware that HDD/SDD hardware vendors use 1000 for KB, not 1024. That's why HDD marked as 400Gb will be shown as 372.53GB in most programs. Be sure you provide your user with information he expects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top