postheadericon Download file in a mobile C# application

I didn't find a tutorial on how to download something on a mobile device in c#, most of the tutorials work with the WebClient class, but that's not in the compact framework mobile apps use. So I found this nice app that came close to what I needed and I took several other parts of code and fused this little example.


//initiate the buffer size (I just took this value from a tutorial and it was large enough for my need
int BufferSize = 32768;

//create a HTTP request of your file and capture the response

           HttpWebRequest request = (HttpWebRequest)WebRequest.Create("");
           HttpWebResponse response = (HttpWebResponse)request.GetResponse();
           Stream readStream = response.GetResponseStream();

//create a buffer

           byte[] ByteBucket = new byte[BufferSize + 1];

//create a filestream to write the local file
          FileStream fileToWrite = new FileStream("", FileMode.Create, FileAccess.Write);
//create a loop to read the downstream in parts and write each part to the wanted file
           bool done = false;
           int currentBytesRead = 0;
           int totalBytesRead = 0;
           while (done == false)
                currentBytesRead = readStream.Read(ByteBucket, 0, BufferSize);
                fileToWrite.Write(ByteBucket, 0, currentBytesRead);
                totalBytesRead += currentBytesRead;
                if (totalBytesRead == response.ContentLength) {
                    done = true;


This was succesfully tested on a Windows CE 5 device.


Last Updated (Thursday, 09 April 2009 15:14)


Add your comment

Your name:
Your email:
Your website: