Skip to content

Download File in .Net Compact Framework

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();
client.DownloadFile(url, destinationFile);

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
class FileDownloader
{
/// 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;

try
{
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;
Debug.WriteLine(exp);
}
finally
{
// cleanup all potentially open streams.

if(null != responseStream)
responseStream.Close();
if(null != response)
response.Close();
if(null != fileStream)
fileStream.Close();
}

// if part of the file was written and the transfer failed, delete the partial file
if (!success && File.Exists(destination))
File.Delete(destination);

return success;
}
}

{ 10 } Comments

  1. wocketfast | May 22, 2008 at 11:29 am | Permalink

    Good looking bit of code, has saved me alot of time! Just adding credentials to it.

    Thanks

  2. Dave Falkner | September 16, 2008 at 9:05 am | Permalink

    Very useful and informative – thanks a bunch for sharing.

  3. Rudi | January 1, 2009 at 1:36 pm | Permalink

    Thank you very much!!!!

  4. s_limak | January 22, 2009 at 6:34 am | Permalink

    Good job!

  5. dexidle | January 29, 2009 at 9:55 pm | Permalink

    You save me alot… good job

  6. Dave | April 9, 2009 at 3:51 pm | Permalink

    You are a lifesaver!

  7. Christopher Palmer | May 4, 2009 at 2:11 pm | Permalink

    Hey! Thanks for this, I’ll be putting it into a Media Lab project on WinMo phones (with a thanks to you).

    I hate the CF.

  8. admin | May 5, 2009 at 6:30 am | Permalink

    I’ve been interested in the media lab for years; you do some really cool projects over there. I’m glad you could incorporate this code.

    I agree with you though: the CF often times felt like there were arbitrary exclusions made; things that should have made it into the SDK that did not. I’ve been doing a lot of iPhone development lately, and its amazing to me how much more feature complete the SDK is versus what is available in the CF. I guess you could always use the MFC or lower level C++ Windows libraries available on WinMo, but that opens an entirely different can of worms, with its own set of discrepancies from the Windows API. Plus I just read that the new Windows Marketplace for mobile apps will be limited to code written for the .Net CF, so it pretty much excludes the use of unmanaged calls to the C apis.

  9. Ariel Padilla | February 18, 2011 at 4:38 pm | Permalink

    Exelente codigo, felicidades y gracias por la aportacion

  10. Glen H | April 21, 2012 at 10:19 am | Permalink

    It’s the code that keeps on giving. Thanks!

{ 1 } Trackback

  1. [...] The code i’m using for the download is based on http://spitzkoff.com/craig/?p=24 [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *