Webclient downloadfileasync not working

依然范特西╮ 提交于 2019-12-11 05:55:39

问题


I got a WPF application and I want to download a file.

I'm using System.Net; and I have the following code:

WebClient ww = new WebClient();
ww.DownloadFileAsync(
    new Uri("http://www.sinvise.net/tester/1.jpg"), 
    AppDomain.CurrentDomain.BaseDirectory + "\\1.jpg");

The problem is, is that it doesn't download the file, it's just showing up as 0kb file and not downloading, I don't know what the problem is, can anyone help?


回答1:


How about listening for the DownloadFileCompleted event and checking the AsyncCompletedEventArgs.Error property the event forwards to your handler?

    public static void DownLoadFileInBackground(string address)
    {
        WebClient client = new WebClient();
        Uri uri = new Uri(address);
        client.DownloadFileCompleted += (sender,e)=>
                                        {
                                            //inspect e here:
                                            //e.Error
                                        };
        client.DownloadProgressChanged += (sender,e)=>
                                          {
                                              //e.ProgressPercentage
                                          };
        client.DownloadFileAsync(uri, "blabla");
    }



回答2:


Some websites block requests that dont have certain headers in the request. In particular one i have found in the past is the "User-Agent" header, try copying a header from a browser request and add it into your WebClient

WebClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");



回答3:


Found the answer, I read that DownloadFile checks the DNS first before anything, if I use an IP address it doesn't do the check and immediately works.

Thanks for everyones help on this though.




回答4:


I would like to add that the DownloadFileAsync method (I can't speak for DownloadFile) does not work when you have an existing and unclosed webrequest for the same file. At least that is my experience. It may be it is not allowed by the framework or server.



来源:https://stackoverflow.com/questions/2496850/webclient-downloadfileasync-not-working

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