-1

I'm trying to display the size of the hard disk space in a progress bar. I already have the sizes show in the progress bar but i'm confused on whether how i am able to display if it would be 'MB,KB,GB,TB' corresponding to the size shown and etc..

So far this is the code i got

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (DriveInfo dir in DriveInfo.GetDrives())
            cmbDrive.Items.Add(dir.ToString());
    }

    private void cmbDrive_SelectedIndexChanged(object sender, EventArgs e)
    {
        DriveInfo Drive_Info = new System.IO.DriveInfo(cmbDrive.Text);

        const int byteConversion = 1024;
        double bytes = Convert.ToDouble(Drive_Info.TotalSize);
        double tSpace = Drive_Info.TotalSize;
        double uSpace;
        uSpace = Drive_Info.TotalSize - Drive_Info.TotalFreeSpace;
        uSpace = Math.Round((uSpace / 1024f) / 1024f / 1024f);
        tSpace = Math.Round((tSpace / 1024f) / 1024f / 1024f);
        double space = Drive_Info.TotalSize;
        double fSpace = Drive_Info.TotalFreeSpace;
        prgSpace.Minimum = 0;
        prgSpace.Maximum = 100;
        prgSpace.Value = (int)Math.Round(100d / tSpace * uSpace);
        prgSpace.CreateGraphics().DrawString(uSpace.ToString() + " Free" + " of " + tSpace.ToString() + " ", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(prgSpace.Width / 2 - 10, prgSpace.Height / 2 - 7));

1 Answers1

0

Add this function somewhere in your class. (Source)

static String BytesToString(long byteCount)
{
    string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
    if (byteCount == 0)
        return "0" + suf[0];
    long bytes = Math.Abs(byteCount);
    int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
    double num = Math.Round(bytes / Math.Pow(1024, place), 1);
    return (Math.Sign(byteCount) * num).ToString() + suf[place];
}

Then, instead of printing the double values, use uSpaceStr and tSpaceStr like defined below.

    long tSpace = Drive_Info.TotalSize;
    long uSpace = Drive_Info.TotalSize - Drive_Info.TotalFreeSpace;
    string uSpaceStr = BytesToString(uSpace);
    string tSpaceStr = BytesToString(tSpace);
    prgSpace.CreateGraphics().DrawString(uSpaceStr + " Free" + " of " + tSpaceStr + " ", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(prgSpace.Width / 2 - 10, prgSpace.Height / 2 - 7));
Community
  • 1
  • 1
Simon Farshid
  • 2,636
  • 1
  • 22
  • 31
  • BytesToString(uSpace) and BytesToString(tSpace) are giving me an argument: 'Cannot convert from double to long' – Captain Yang Sep 11 '14 at 02:59
  • @user3904439 Remove your current definition of tSpace and uSpace, I update my code so it uses `long` instead of `double` – Simon Farshid Sep 11 '14 at 14:34
  • Thank you! It works now! What's left is trying to figure out how to center the text, i will have to do some research with this. – Captain Yang Sep 12 '14 at 02:24