///
/// Download a file from a URL to a local folder on a windows mobile device
/// Note: Don't forget that mobile folders do not start with a drive letter.
///
/// e.g. http://www.someaddress/downloads/
/// e.g. filetodownload.exe
/// e.g. \temp\
///
public static long FromHttp(string uri, string filename, string localFolder)
{
long totalBytesRead = 0;
const int blockSize = 4096;
Byte[] buffer = new Byte[blockSize];
if (!Directory.Exists(localFolder))
{
Directory.CreateDirectory(localFolder);
}
try
{
HttpWebRequest httpRequest =
(HttpWebRequest)WebRequest.Create(Path.Combine(uri, filename));
httpRequest.Method = "GET";
// if the URI doesn't exist, an exception will be thrown here...
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
using (Stream responseStream = httpResponse.GetResponseStream())
{
using (FileStream localFileStream =
new FileStream(Path.Combine(localFolder, filename), FileMode.Create))
{
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytesRead += bytesRead;
localFileStream.Write(buffer, 0, bytesRead);
}
}
}
}
}
catch (Exception ex)
{
// You might want to handle some specific errors : Just pass on up for now...
throw;
}
return totalBytesRead;
}
Comments welcome.