NoWar
NoWar

Reputation: 37633

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)
            {

            }
        }

Upvotes: 2

Views: 5681

Answers (2)

Halis S.
Halis S.

Reputation: 446

By declaring Main function as async, you can also use DownloadFileTaskAsync with await.

public static async void Main(string[] args)
{
    var urlAddress = "http://mywebsite.com/msexceldoc.xlsx";
    var fileName = @"D:\1.xlsx";

    using (var client = new WebClient())
    {
        await client.DownloadFileTaskAsync(new Uri(urlAddress), fileName);
    }
}

Upvotes: 3

Simon
Simon

Reputation: 1081

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.

Upvotes: 6

Related Questions