Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


Download a file from the internet in C#
This code will download a file from the internet, while simultaneously updating a progress bar with the percent downloaded. Neat!

Main Thread:


using System.Threading;
using System.Net;

.......

ThreadStart ts = new ThreadStart(StartTimerThread);
this.myTimerThread = new Thread(ts);
myTimerThread.Start(); // This Thread will download the file
while(myTimerThread.IsAlive)
{ // Meanwhile, UI will keep track of the state of the download (progress bar)
if(System.IO.File.Exists(saveToFile))
{
System.IO.FileInfo info = new System.IO.FileInfo(saveToFile);
long size = info.Length;
long progress = (100*size)/_fileSize;
progBar.Value = (int)progress;
DoPause(.5); // call Application.DoEvents to refresh the progress bar in a pause function!
}
} // while thread is alive
this.progBar.Value = 100;
DoPause(0); // call Application.DoEvents to refresh the progress bar in a pause function!

The Thread that does all the work runs this function:

private void StartTimerThread()
{
try
{
mainClient = new WebClient();
mainClient.DownloadFile(remoteFilePath, localFilePathBeingDownload);
}
catch{}
finally
{
if(mainClient != null)
mainClient.Dispose();
}
} // StartTimerThread

You'll need to initialize the progress bar's maximum as the size of the file: Here's how to get that:

// get length
System.Net.WebRequest request = null;
WebResponse response = null;
try
{
request = WebRequest.Create(remoteFilePath);
response = request.GetResponse();
WebHeaderCollection headers = response.Headers;
string length = headers.Get("Content-Length");
if(length==""length==null)
length="0";
updateFileSize = int.Parse(length);
}
catch{}
finally
{
if(response!=null)
response.Close();
if(request!=null)
request.Abort();
}


Since myTimerThread and mainClient are defined at the class level, it will be easy to build a cancel button that simply kills the thread and disposes the client, thus aborting the main loop and ending the download.

private void btnCancel_Click(object sender, System.EventArgs e)
{
bCancel = true;
this.myTimerThread.Abort();
if(mainClient!=null)
mainClient.Dispose();
}

Created By: amos 3/20/2006 12:13:00 AM