【问题标题】:WebClient not downloading full file?WebClient没有下载完整文件?
【发布时间】:2015-08-25 18:45:37
【问题描述】:

我有一个WebClient 正在下载一个 .chm 文件(如下面的代码所示)。下载的内容似乎非常不规则。完整文件大小约为 2500-2600 KB,但大约 50-75% 的时间我会返回较小的文件(一些示例:1233 KB、657 KB、353 KB、1745 KB 等)。
(代码已简化/个人详细信息已删除)

public static void DownloadMyFile(string destFileAndPath)
{
    //Get base for help Url, stop at first "/" ignoring "https://", then add path in server
    string Url = "https://mywebservice.com/myFile.chm";

    using (var client = new WebClient())
    {
        //I need to do stuff to the downloaded file when done
        client.DownloadFileCompleted += client_DownloadFileCompleted;

        client.DownloadFileAsync(new Uri(Url), destFileAndPath);

        //More waiting?
        while (client.IsBusy) { }
    }
}

还有事件,它工作正常,但在一个“未完成”的文件上:

public static void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    //Do stuff like comparing the file to another, renaming, copying, etc.
}  

我真的错过了什么吗?

【问题讨论】:

  • 您是否在检查AsyncCompletedEventArgs e 的内容,尤其是CancelledError 属性?
  • 啊!我只是检查Cancelled。看起来Error 正在返回,但有某种异常(我将不得不进一步调查)。

标签: c# webclient downloadfileasync


【解决方案1】:

看起来 Paul Roub 的评论让我找到了正确的解决方案。我只是检查e.Cancelled 属性。

有时会抛出异常(主要是某种WebException),这会导致下载出错。一旦我检查了 e.Error 属性,我就可以重试或处理失败的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多