16 Jun

Download Files Synchronous And Asynchronous From A URL in C#

This page tells how to download files from any url to local disk. To download the files, We use WebClient class in System.Net namespace. This class supports to the synchronous and asynchronous downloads. Following examples show how to download files as synchronous and asynchronous.

This example downloads the resource with the specified URI to a local file.

            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadFile("http://www.example.com/file/test.jpg", "test.jpg");
            }

This example downloads to a local file, the resource with the specified URI. Also this method does not block the calling thread.

            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e)
                    {
                        Console.WriteLine("Downloaded:" + e.ProgressPercentage.ToString());
                    });

                webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler
                    (delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
                    {
                        if(e.Error == null && !e.Cancelled)
                        {
                            Console.WriteLine("Download completed!");
                        }
                    });
                webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
            }

5 thoughts on “Download Files Synchronous And Asynchronous From A URL in C#

  1. Pingback: How to download a file from a URL in C#? | ASK AND ANSWER

Leave a Reply

Your email address will not be published. Required fields are marked *