我使用WebClient.DownloadFile(address,fileName)类下载一个文件。
我用秒表计算下载速度。
我的速度计算代码;
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等...”格式,但是我的代码仅提供“ kb / s”格式。如何显示其他格式?
答案 0 :(得分:2)
您可以使用Enum来避免克隆显示代码。这里是一个例子:
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
答案 1 :(得分:0)
好的,我现在仅通过这种方式就解决了我的问题;
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;