I need basic file downloading capabilities in my app and I cannot use WebClient.DownloadFile [1]. Is this (naïve?) implementation of a DownloadFile method enough? Are there any pitfalls that I don’t address with this implementation?
public static void DownloadFile(String url, String destination)
{
using (var request = (HttpWebRequest)WebRequest.Create(url))
{
request.Method = "GET";
request.Timeout = 100000; // 100 seconds
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var fileStream = File.Open(destination,
FileMode.Create,
FileAccess.Write,
FileShare.None))
{
var MaxBytesToRead = 10 * 1024;
var buffer = new Byte[MaxBytesToRead];
var totalBytesRead = 0;
var bytesRead = responseStream.Read(buffer,
0,
MaxBytesToRead);
while (bytesRead > 0)
{
totalBytesRead += bytesRead;
fileStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer,
0,
MaxBytesToRead);
}
}
}
}
}
}
Thanks!
[1] .Net Compact Framework…
You’re keeping track of
totalBytesRead, but I can’t see it used anywhere.Since
Method = "GET"is the default, I don’t see anything that’s specific to HTTP. If you remove the(HttpWebRequest)cast and theMethod =line then you’ll gain the ability to download over other protocols, such as FTP. Currently the code will throw an exception if somebody provides a URL other than http://.