2015-05-01 63 views
1

我的代碼連接互聯網在C#中下載的文件是:顯示錯誤消息不WebClient的

private void Completed(object sender, AsyncCompletedEventArgs e) 
    { 
     MessageBox.Show("Download completed!"); 
    } 
    //----------- Download complete 
    Stopwatch sw = new Stopwatch(); 
    private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
    {// Calculate download speed and output it to labelSpeed. 
     lblspeed.Text = string.Format("{0} kb/s", (e.BytesReceived/1024d/sw.Elapsed.TotalSeconds).ToString("0.00")); 
     // Update the progressbar percentage only when the value is not the same. 
     progressBar.Value = e.ProgressPercentage;// Show the percentage on our label. 
     lblper.Text = e.ProgressPercentage.ToString() + "%";// Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading 
     lblsize.Text = string.Format("{0} MB’s/{1} MB’s", 
     (e.BytesReceived/1024d/1024d).ToString("0.00"), 
     (e.TotalBytesToReceive/1024d/1024d).ToString("0.00")); 
    } 
    public void DownloadFile(string urlAddress, string location) 
    { 
     using (WebClient client = new WebClient()) 
     { 
      client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); 
      client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);// The variable that will be holding the url address (making sure it starts with http://) 
      Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("http://" + urlAddress);// Start the stopwatch which we will be using to calculate the download speed 
      sw.Start(); 
      try 
      { 
       // Start downloading the file 
       client.DownloadFileAsync(URL, location); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 
    } 

當我沒有連接到互聯網並調用DownloadFile方法,應用信息:下載完成!

有什麼問題?

回答

0

您需要檢查下載過程中是否發生錯誤。事情是這樣的:

private void Completed(object sender, AsyncCompletedEventArgs e) 
{ 
    if(!e.Cancelled && e.Error == null) 
    MessageBox.Show("Download completed!"); 
}