Downloading a remote file with vb.net / c# using WebClient

Can you believe it’s 2013 already? Me either. Anyhow, just wanted to provide a simple solution for a very popularly asked question: “how can I download a remote file?.” Well, below is a basic method using the WebClient class. It’s pretty cut and dry, just pass a remote file (ie: http://www.chrisbitting.com/image.jpg) and a local file (c:\temp\file.jpg) and it downloads. If you’re interested how to do this with cookies enabled for authentication, let me know!

vb.net

Private Sub dloadhttpFile(fileToDownload As String, localFile As String)
        'Examples:
        'fileToDownload = http://www.chrisbitting.com/image.jpg
        'localFile = c:\files\someimage.jpg

        Try
            'create an instance of WebClient - the heart of downloading a file
            Dim fileReader As New WebClient()

            'check if the file already exists locally
            If Not (System.IO.File.Exists(localFile)) Then
                fileReader.DownloadFile(fileToDownload, localFile)
            End If
        Catch ex As HttpListenerException
            Console.WriteLine(("Error Downloading: " & fileToDownload & " - ") + ex.Message)
        Catch ex As Exception
            Console.WriteLine(("Error Downloading: " & fileToDownload & " - ") + ex.Message)
        End Try
    End Sub

c#

   private void dloadhttpFile(string fileToDownload, string localFile)
        {
             //Examples:
             //fileToDownload = http://www.chrisbitting.com/image.jpg
             //localFile = c:\files\someimage.jpg

            try
            {
                //create an instance of WebClient - the heart of downloading a file
                WebClient fileReader = new WebClient();

                //check if the file already exists locally
                if (!(System.IO.File.Exists(localFile)))
                {
                    fileReader.DownloadFile(fileToDownload, localFile);
                }
            }
            catch (HttpListenerException ex)
            {
                Console.WriteLine("Error Downloading: " + fileToDownload + " - " + ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Downloading: " + fileToDownload + " - " + ex.Message);
            }
        }
Downloading a remote file with vb.net / c# using WebClient

Leave a comment