How To Use HttpWebRequest/Response To Download A Binary (.exe) File From A Web Server?

Jan Tacci picture Jan Tacci · Jan 7, 2013 · Viewed 70.2k times · Source

I am writing a program that needs to download an .exe file from a website and then save it to the hard drive. The .exe is stored on my site and it's url is as follows (it's not the real uri just one I made up for the purpose of this question):

http://www.mysite.com/calc.exe

After many web searches and fumbling through examples here is the code I have come up with so far:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(http://www.mysite.com/calc.exe);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();               
StreamReader streamReader = new StreamReader(responseStream);
string s = streamReader.ReadToEnd();

As you can see I am using the StreamReader class to read the data. After calling ReadToEnd does the stream reader contain the (binary) content of my .exe? Can I just write the content of the StreamReader to a file (named calc.exe) and I will have succesfully downloaded the .exe?

I am wondering why StreamReader ReadToEnd returns a string. In my case would this string be the binary content of calc.exe?

Answer

Dipu picture Dipu · Nov 29, 2014

WebClient is the best method to download file. But you can use the following method to download a file asynchronously from web server.

private static void DownloadCurrent()
{
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("[url to download]");
    webRequest.Method = "GET";
    webRequest.Timeout = 3000;
    webRequest.BeginGetResponse(new AsyncCallback(PlayResponeAsync), webRequest);
}

private static void PlayResponeAsync(IAsyncResult asyncResult)
{
    long total = 0;
    long received = 0;
    HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;

    try
    {                    
        using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
        {
            byte[] buffer = new byte[1024];

            FileStream fileStream = File.OpenWrite("[file name to write]");
            using (Stream input = webResponse.GetResponseStream())
            {        
                total = input.Length;

                int size = input.Read(buffer, 0, buffer.Length);
                while (size > 0)
                {
                    fileStream.Write(buffer, 0, size);
                    received += size;

                    size = input.Read(buffer, 0, buffer.Length);
                }
            }

            fileStream.Flush();
            fileStream.Close();
        }                 
    }
    catch (Exception ex)
    {
    }
}

There is a similar thread here - how to download the file using httpwebrequest