2

我有一个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.
}  

我真的在这里错过了什么吗?

4

1 回答 1

1

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

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

于 2015-10-08T16:24:57.917 回答