Due to the fact that the .Net Compact Framework has a stripped down version of System.Net, the class System.Net.WebClient is not present. This complicates certain tasks that were simple on the desktop, such as downloading a file from the web.
On the desktop, something like this would work just fine for certain applications:
System.Net.WebClient client = new WebClient();
Unfortunately, that’s not a possibility in the compact framework. You’ve got to use WebRequest objects and IO streams, etc. But I kind of like the idea of a single function call to download a file and send it to a destination on disk, so I threw together the following .Net class in C# for your enjoyment.
/// Class used to download files from the web when System.Net.WebClient
/// is unavailable
/// Download a file from the web.
/// url - URL of the file to download
/// destination - Full path of the destination of the file we are downloading
/// returns - flag indicating whether the file download was successful
public static bool DownloadFile(string url, string destination)
bool success = false;
System.Net.HttpWebRequest request = null;
System.Net.WebResponse response = null;
Stream responseStream = null;
FileStream fileStream = null;
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
request.Method = "GET";
request.Timeout = 100000; // 100 seconds
response = request.GetResponse();
responseStream = response.GetResponseStream();
fileStream = File.Open(destination, FileMode.Create, FileAccess.Write, FileShare.None);
// read up to ten kilobytes at a time
int maxRead = 10240;
byte buffer = new byte[maxRead];
int bytesRead = 0;
int totalBytesRead = 0;
// loop until no data is returned
while ((bytesRead = responseStream.Read(buffer, 0, maxRead)) > 0)
totalBytesRead += bytesRead;
fileStream.Write(buffer, 0, bytesRead);
// we got to this point with no exception. Ok.
success = true;
catch (Exception exp)
// something went terribly wrong.
success = false;
// cleanup all potentially open streams.
if(null != responseStream)
if(null != response)
if(null != fileStream)
// if part of the file was written and the transfer failed, delete the partial file
if (!success && File.Exists(destination))