【问题标题】:showing error message for don't connect the internet in webclient in c#在 c# 中的 webclient 中显示不连接互联网的错误消息
【发布时间】:2015-05-01 07:20:40
【问题描述】:

我的下载文件代码是:

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方法时,应用消息:下载完成!!!

有什么问题?

【问题讨论】:

    标签: exception download webclient connect


    【解决方案1】:

    您需要检查下载过程中是否出现错误。像这样的:

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

    【讨论】:

      猜你喜欢
      • 2019-12-13
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 2019-10-15
      • 2016-07-09
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      相关资源
      最近更新 更多