Search code examples
c#.netwebclientdownloadfileasync

WebClient DownloadFileAsync() does not work


WebClient DownloadFileAsync() does not work with the same URl and Credentials...

Any clue?

 static void Main(string[] args)
        {
            try
            {
                var urlAddress = "http://mywebsite.com/msexceldoc.xlsx";


                using (var client = new WebClient())
                {
                    client.Credentials = new NetworkCredential("UserName", "Password");
                    // It works fine.  
                    client.DownloadFile(urlAddress, @"D:\1.xlsx");
                }

                /*using (var client = new WebClient())
                {
                   client.Credentials = new NetworkCredential("UserName", "Password");

                    // It y creats file with 0 bytes. Dunow why is it. 
                    client.DownloadFileAsync(new Uri(urlAddress), @"D:\1.xlsx");
                    //client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);

                }*/
            }
            catch (Exception ex)
            {

            }
        }

Solution

  • You need to keep the program running while the async download completes, as it runs in another thread.

    Try something like this, and wait for it to say completed before you hit enter to end the program:

    static void Main(string[] args)
        {
            try
            {
                var urlAddress = "http://mywebsite.com/msexceldoc.xlsx";
    
                using (var client = new WebClient())
                {
                   client.Credentials = new NetworkCredential("UserName", "Password");
    
                    client.DownloadFileAsync(new Uri(urlAddress), @"D:\1.xlsx");
                    client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
            }
            catch (Exception ex)
            {
    
            }
    
        Console.ReadLine();
        }
    
    public static void Completed(object o, AsyncCompletedEventArgs args)
    {
        Console.WriteLine("Completed");
    }
    

    Depending what kind of app you're using this in, the main thread needs to keep running while the background thread downloads the file.