WebClient - DownloadFileAsync not working when called second time

雨燕双飞 提交于 2019-12-13 06:49:04

问题


I've build simple method that downloads single file. When I call that method first time everything works fine, but when called second time file isn't downloaded.
Below is my code:

public void DownloadFile(string fileUrl, string path)
{
    using (var webClient = new WebClient())
    {
        webClient.DownloadFileCompleted += (sender, e) =>
        {
            if (e.Error == null & !e.Cancelled)
            {
                Debug.WriteLine(@"Download completed!");
            }
        };

        var url = new Uri(fileUrl);

        try
        {
            webClient.OpenRead(url);
            string headerContentDisposition = webClient.ResponseHeaders["content-disposition"];
            string filename = new ContentDisposition(headerContentDisposition).FileName;

            Debug.WriteLine(filename);

            path = Path.Combine(path, filename);
            webClient.DownloadFileAsync(url, path);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

I've identified part that is breaking my download, it is part that is responsible for getting file name:

webClient.OpenRead(url);
string headerContentDisposition = webClient.ResponseHeaders["content-disposition"];
string filename = new ContentDisposition(headerContentDisposition).FileName;

If I replace that part with string filename = "1.tmp"; I'm able to call my method multiple times without errors.

I'm calling that method by clicking button with this click event:

private void button1_Click(object sender, EventArgs e)
{
    const string url = @"http://www.jtricks.com/download-text";
    const string target = @"D:\TEMP\";
    DownloadFile(url, target);
}

After two click on button without code that is getting file name I get this output in console:

1.tmp
Download completed!
1.tmp
Download completed!

Below is gif showing this working fine:

When I add back part that is getting file name this is my output:

content.txt
Download completed!
content.txt

Below gif showing that behavior:

Second time I click Start I'm getting file name, but download don't start, next click blocks start button.

How can I fix this? Ideally I'd like to call DownloadFile as many time I need.


回答1:


It seems that WebClientis using a Cache. I suggest that you have to tell WebClient not to use caching:

webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);


来源:https://stackoverflow.com/questions/39640955/webclient-downloadfileasync-not-working-when-called-second-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!