Thursday 16 February 2006

WebRequest/WebResponse and saving a downloaded binary

It took waay longer than I expected to find this code on Google... Sure you can use WebClient with it's DownloadFile() method... but if you want to fiddle with timeout settings, etc. then you need to drop back to the WebRequest/WebResponse classes.

Thanks to this GoogleGroups response download binary file using c# webrequest/webresponse I was able to get it working.
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
objRequest.Timeout = 600000;
objRequest.Credentials = CredentialCache.DefaultCredentials;
WebResponse objResponse = objRequest.GetResponse();
byte[] buffer = new byte[32768];
using (Stream input = objResponse.GetResponseStream())
{
using (FileStream output = new FileStream (fileloc, FileMode.CreateNew))
{
int bytesRead;
while ( (bytesRead=input.Read (buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
There are all sorts of red-herrings around this task - BinarySteam, ResponseEncoding, etc... but in the end it was relatively simple.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.