我在C#中有拨号程序。如果正在下载/上传,我想更改图像。如何在以下代码中添加此类检查?
private void UpdateNetworkInterface()
{
this.Invoke((MethodInvoker)delegate
{
NetworkInterface nic = nicArr[cmbInterface.SelectedIndex];
IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();
long lngBytesSent = 0;
long lngBtyesReceived = 0;
int bytesSentSpeed = (int)(interfaceStats.BytesSent - lngBytesSent) /1024;
int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - lngBtyesReceived) /1024;
// Update the labels
lblInterfaceType.Text = nic.NetworkInterfaceType.ToString();
lblUpload.Text = bytesSentSpeed.ToString() + " KB";
lblDownload.Text = bytesReceivedSpeed.ToString() + " KB";
//this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n DOWNLOAD/UPLOAD in progress", ""));
});
}
答案 0 :(得分:0)
您可以使用System.Net.WebClient
来执行此操作。
它有一个事件DownloadProgressChanged
,它有参数,它有包含下载字节和文件总字节数的字段。
由WebClient.DownloadFileAsync()
触发。
MSDN链接:https://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx
示例:
private void DownloadChanged(object sender, DownloadProgressChangedEventArgs e)
{
labelProgress.Text = string.Format("{0} Percents Completed",
e.BytesReceived / e.TotalBytesToReceive * 100);
}
private void StartDownload(object sender, EventArgs e) // Button Event
{
var webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadChanged);
webClient.DownloadFileAsync(/* URL */);
}
获取上传字节与下载一个相同。快乐编程! :)
答案 1 :(得分:0)
这些属性为您提供转移的总字节数,您需要的是该数字的衍生物(变化率)。
最简单的方法就是做简单的数学问题
所以你需要录音然后比较这两点以获得速度。
private long _lastBytesRecevied;
private long _lastBytesSent;
private DateTime _lastReceivedMesurement;
private DateTime _lastSentMesurement;
//This needs to be done once at the start of the class to "seed" the first value.
private Init()
{
_lastReceivedMesurement = DateTime.UtcNow;
_lastBytesRecevied = interfaceStats.BytesReceived;
_lastSentMesurement = DateTime.UtcNow;
_lastBytesSent = interfaceStats.BytesSent;
}
private double getKBDownloadSpeed()
{
double result = (interfaceStats.BytesReceived - _lastBytesRecevied) / (DateTime.UtcNow - _lastReceivedMesurement).TotalSeconds;
_lastReceivedMesurement = DateTime.UtcNow;
_lastBytesRecevied = interfaceStats.BytesReceived;
return result / 1024d;
}
private double getKBUploadSpeed()
{
double result = (interfaceStats.BytesSent - _lastBytesSent) / (DateTime.UtcNow - _lastSentMesurement).TotalSeconds;
_lastSentMesurement = DateTime.UtcNow;
_lastBytesSent = interfaceStats.BytesSent;
return result / 1024d;
}
现在,您的两个函数返回上次调用函数和当前调用之间的平均下载速度。
如果您获得下载速度的价值,请将图像更改为下载图标。 如果您获得上传速度的值,请将图像更改为上传图标。
此致
Thiyagu Rajendran
**如果有帮助,请将回复标记为答案。