Quick & Dirty: Download A File From The Internet

Here’s a quick and dirty way to download a file from the internet:

public bool DownloadFile(string sourceUrl, string targetFilePath)


      byte[] buff = new byte[MASSIVE_NUMBER];




            WebRequest req = WebRequest.Create(sourceUrl);

            WebResponse response = req.GetResponse();

            Stream stream = response.GetResponseStream();

            BinaryReader br = new BinaryReader(stream);


            buff = br.ReadBytes(MASSIVE_NUMBER);




            FileStream fs = new FileStream(



            fs.Write(buff, 0, buff.Length);



      catch (Exception e)


            Debug.WriteLine(“Exception: {0}”, e.Message);


            return false;




      return true;





It looks like practically the entire function is in the try-block. Let me say that I vehemently discourage the indiscriminate wrapping of the entirety of functions in try/catch blocks as a form of ‘protection’. If you practice that, I suggest you stop it yesterday. Anyway, as for the above sample, practically all the code in the function can clap-out due to I/O errors, which is one of the very very few true exceptions. So that is why, they’re all in the try-block.

As you can see, it is a very quick, and dirty way to download a file from the internet. Quick, because the code is short and simple. Dirty, because it is synchronous, and attempts to just read the whole file by asking for some massive number that should be larger than the file in question. Do use a suitably big but not excessively large MASSIVE_NUMBER number as this dirty way allocates a buffer with it.

This entry was posted in Uncategorized. Bookmark the permalink.

4 Responses to Quick & Dirty: Download A File From The Internet

  1. ssteo says:

    haha even simpler and dirtier way:

    public bool DownloadFile(string url, string filename)
    new WebClient().DownloadFile(url, filename);

    return true;
    catch(Exception ex)
    Debug.WriteLine(“Exception: {0}”, ex.Message);
    return false;

  2. ssteo says:

    add-on, requires:

    using System.Net;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s