Downloading File in .NET CF
2012-03-23 by
This is actually quite simple. Here is a sample that should help with the Binary Reader/Writer.
private void DownloadFile(string downloadfilename, string rootDir, string folderName, string url)
{
string serverPath = System.IO.Path.GetDirectoryName(downloadfilename);
string localDir = System.IO.Path.Combine(rootDir,serverPath);
string localFile = System.IO.Path.Combine(rootDir, downloadfilename);
if (!System.IO.Directory.Exists(localDir))
System.IO.Directory.CreateDirectory(localDir);
string fileName = url + "/" + folderName + "/" + downloadfilename.Replace("\\", "/");
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(fileName);
webRequest.Method = "GET";
System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
System.IO.BinaryReader reader = new System.IO.BinaryReader(webResponse.GetResponseStream());
long remaining = webResponse.ContentLength;
int bufferLength = 256;
byte[] buffer = new byte[bufferLength];
if (System.IO.File.Exists(localFile))
System.IO.File.Delete(localFile);
System.IO.FileStream stream = new System.IO.FileStream(localFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
while(remaining>0)
{
buffer = reader.ReadBytes(bufferLength);
stream.Write(buffer, 0, buffer.Length);
remaining -= buffer.Length;
}
stream.Close();
reader.Close();
}