Skip to main content
 首页 » 编程设计

c#之WebClient下载文件异步不起作用

2024年01月21日27langtianya

我有一个WPF应用程序,我想下载一个文件。

我正在使用System.Net;而且我有以下代码:

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


问题是,它不会下载文件,只是显示为0kb文件而不下载,我不知道问题出在哪,有人可以帮忙吗?

请您参考如下方法:

侦听DownloadFileCompleted事件并检查该事件转发给处理程序的AsyncCompletedEventArgs.Error属性如何?

    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"); 
    }