问题
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 WebClient
is 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