如何确定大小是否为KB,MB,GB,TB进度条?

时间:2014-09-10 05:59:51

标签: c# progress-bar

我正在尝试在进度条中显示硬盘空间的大小。我已经在进度条中显示了尺寸,但我很困惑我是否能够显示它是否与显示的尺寸相对应的“MB,KB,GB,TB”等等。

到目前为止,这是我得到的代码

    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 个答案:

答案 0 :(得分:0)

在班级的某处添加此功能。 (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];
}

然后,不要打印双值,而是使用uSpaceStrtSpaceStr,如下所示。

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