秒表下载速度与其他速度格式计算

Stopwatch download speed calculate with other speed formats

我正在下载一个 WebClient.DownloadFile(address, fileName) class.

的文件

我用秒表计算下载速度。

我的速度计算代码;

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
labelSpeed.Text = string.Format("{0} kB/s", (e.BytesReceived / 1024 / stopWatch.Elapsed.TotalSeconds).ToString("0.00"));

我想显示下载速度 "b/s, kb/s, mb/s, gb/s, etc..." 格式,但我的代码只提供 "kb/s" 格式。如何显示其他格式?

好的,我暂时用这种方法简单地解决了我的问题;

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

string downloadSpeed;

downloadSpeed = string.Format("{0} B/s", (e.BytesReceived / stopWatch.Elapsed.TotalSeconds).ToString("0.00"));
if ((e.BytesReceived / stopWatch.Elapsed.TotalSeconds) > 1024)
{ downloadSpeed = string.Format("{0} KB/s", (e.BytesReceived / 1024 / stopWatch.Elapsed.TotalSeconds).ToString("0.00")); }
if ((e.BytesReceived / 1024 / stopWatch.Elapsed.TotalSeconds) > 1024)
{ downloadSpeed = string.Format("{0} MB/s", (e.BytesReceived / 1024 / 1024 / stopWatch.Elapsed.TotalSeconds).ToString("0.00")); }
if ((e.BytesReceived / 1024 / 1024 / stopWatch.Elapsed.TotalSeconds) > 1024)
{ downloadSpeed = string.Format("{0} GB/s", (e.BytesReceived / 1024 / 1024 / 1024 / stopWatch.Elapsed.TotalSeconds).ToString("0.00")); }

labelSpeed.Text = downloadSpeed;

您可以使用枚举来避免克隆显示代码。举个例子:

enum ByteMassFactor { B = 1, KB = 1024, MB = 1024 * 1024, GB = 1024 * 1024 * 1024 }

void Main()
{
    var byteCount = 2048;

    foreach (var mass in Enum.GetValues(typeof(ByteMassFactor)).Cast<ByteMassFactor>().Reverse())
        if (byteCount / (int)mass >= 1)
        {
            Console.WriteLine($"{byteCount / (int)mass} {mass}");
            break;
        }
}

输出:

2 KB