Search

Tuesday, November 17, 2009

How to Download file in .NET compact frame work windows mobile ?

if you are desktop developer you know there is api "WebClient" to download a file from the web unfortunately in .netcf that api is absent but there is a alternative way of doing it by using IO streams and download a file see the below code snippet


public static bool fileDownloadDotNetCF(string url)
{
bool success = false;
string destination = getPath();
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 + "\\temp.CAB", 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.
MessageBox.Show(exp.ToString(), "Error Could not Download the file");
success = false;

}
finally
{

// cleanup all open streams.

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

// if data transfer fails in between file download delet the
// partially downloaded file
if (!success && File.Exists(destination))
File.Delete(destination);

return success;
}

I dont know why wm .netcf team stripped such a important api from compact framework not only this there are tons of such API's which are very required and useful but not incorporated in compact framework.

0 comments:

Post a Comment

Other Interesting Articles



Related Article Widget by Yogith

Search Powered by Google