我正在使用C#创建一个Windows应用程序。它用于检查产品的任何更新版本是否可用。如果是,用户只能使用应用程序的UI下载它而无需打开任何浏览器。
应用程序中的一个窗口使用ProgressBar控件显示下载状态。问题是,如果互联网断开连接,应用程序就不会知道了。比如说,在45%的下载后,网络断开连接;但ProgressBar继续显示45%。
一旦出现这种情况,是否会引发任何财产/事件?请帮忙。附上我的代码以供参考。感谢。
private void CheckForUpdate_Load(object sender, EventArgs e)
{
string downloadURL = Convert.ToString(ConfigurationManager.AppSettings["TempDownloadURL"]);
WebClient wcDownloadFile = new WebClient();
Uri myUri = new Uri(downloadURL);
wcDownloadFile.DownloadFileAsync(myUri, downloadLocation);
wcDownloadFile.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownloadFile_DownloadProgressChanged);
}
void wcDownloadFile_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
int bytesDownloaded = Int32.Parse(e.BytesReceived.ToString());
int totalBytes = Int32.Parse(e.TotalBytesToReceive.ToString());
progBarSoftPhone.Value = e.ProgressPercentage;
lblStatus.Text = (bytesDownloaded / 1024).ToString() + " KB out of " + (totalBytes / 1024).ToString() + " KB downloaded (" + e.ProgressPercentage.ToString() + "%).";
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
答案 0 :(得分:2)
您可以使用NetworkChange.NetworkAvailabilityChanged事件 http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.networkavailabilitychanged.aspx 如果局域网出现问题,它将告诉您,例如:网络电缆已拔下或用户自己禁用NetworkInterface。
如果因特网掉线,你需要对你自己的服务器有一些ping机制来检查服务器是否可以访问,你可以在开始下载ping时启动一个定时器,并定期检查直到下载完成,下载完成或用户取消后,您可以停止计时器。
答案 1 :(得分:1)
为DownloadFileCompleted事件添加事件侦听器,并检查AsyncCompletedEventArgs的Error属性。
在CheckForUpdate_Load方法中添加:
wcDownloadFile.DownloadFileCompleted += WebClOnDownloadFileCompleted;
然后在处理程序中,您可以在发生错误时停止进度条:
private void WebClOnDownloadFileCompleted(object sender,
AsyncCompletedEventArgs asyncCompletedEventArgs)
{
if (asyncCompletedEventArgs.Error != null)
// code to handle it
}