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?
StreamReader is a text reader implementation i.e. it should be used to read text data and not binary data. In your case, you should be directly using the underlying response stream.
For downloading file, the simplest way would be to use WebClient.DownloadFile method.
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
This should directly save the file on your hard disk.
using System.Net;
using (WebClient webClient = new WebClient ())
{
webClient.DownloadFile("http://www.mysite.com/calc.exe", "calc.exe");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With