System.Net.WebClient.DownloadFileAsync Method

.NET Class Library Documentation

DownloadFileAsync Method

Asynchronously downloads a resource from a server and saves it to a local file.

public virtual void DownloadFileAsync (Uri address, string fileName);

public virtual void DownloadFileAsync (string address, string fileName);

public virtual void DownloadFileAsync (Uri address, string fileName, object userToken);

public virtual void DownloadFileAsync (string address, string fileName, object userToken);

Parameters

address
A Uri object that specifies the resource to download.
fileName
A String that specifies the local file name to save the resource to.
userToken
(Optional) A user-defined object that distinguishes between multiple asynchronous requests.

Remarks

The DownloadFileAsync method is used to download a resource from a URI asynchronously. This method does not block the calling thread. Use this method when you want to download a file and continue with other operations while the download is in progress.

When the download operation completes, the DownloadFileCompleted event is raised.

You can check the Cancelled property of the AsyncCompletedEventArgs parameter in the event handler to determine if the operation was cancelled.

The userToken parameter can be used to associate a unique object with the asynchronous request. This is useful if you have multiple concurrent asynchronous requests and need to distinguish them in the event handler.

Important

Ensure that the file name specified in the fileName parameter is a valid path and that the application has the necessary write permissions for that location. If the file already exists, it will be overwritten.

Note

For modern asynchronous programming patterns, consider using the DownloadFileTaskAsync method, which returns a Task and integrates better with async/await.

Examples

Download a file asynchronously
using System;
using System.Net;
using System.ComponentModel;

public class Example
{
    private static WebClient webClient;

    public static void Main(string[] args)
    {
        webClient = new WebClient();
        string url = "https://www.example.com/somefile.zip";
        string filePath = "downloadedfile.zip";

        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallback);

        try
        {
            Console.WriteLine($"Starting download from {url} to {filePath}...");
            webClient.DownloadFileAsync(new Uri(url), filePath);
            // Keep the console application running until the download completes
            Console.WriteLine("Download initiated. Press Enter to exit.");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
        finally
        {
            webClient.Dispose();
        }
    }

    private static void DownloadFileCallback(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Cancelled)
        {
            Console.WriteLine("Download cancelled.");
        }
        else if (e.Error != null)
        {
            Console.WriteLine($"Error during download: {e.Error.Message}");
        }
        else
        {
            Console.WriteLine("Download completed successfully!");
        }
    }
}

See Also