Code Project Pick: “HTTP File Downloader Class for .NET”


HTTP File Downloader Class for .NET
Click title for source at CodeProject.com…

By Alex_1




Introduction
This short article presents the component HttpFileDownloader for .Net

It was designed a few years ago, that is why it is written for .NET 1.1

However it can be used for newer frameworks or/and recompiled.

It shows the estimated time left and the progress.

The component can be used with Windows forms application and with console/service apps.
If used in a windowless environment, “null” should be passed to the constructor
instead of “this”. The code is very simple to use and understand.

Using the code
Create the instance of the component and the event handler.

_FileDownloader = new DotNetFileDownloader(this);

// "this" required only for Windows Forms Component/App 

_FileDownloader.URLDownload = textBox_url.Text; // set the URL to download

// setting local path

_FileDownloader.LocalFilePath = textBox_local_folder.Text + "\\" + FileName ;// setting the downloading status event handler

_FileDownloader.UpdateStatusEvent +=new UpdateDelegate(_FileDownloader_UpdateStatusEvent);

The status event handler is pretty straightforward

string Message,

DStatus Status,

long FullSize,

long CurrentBytes,

TimeSpan EstimatedTimeLeft)

{

    label_status.Text = Message + "\n" + Status.ToString();

    if (FullSize != 0 && FullSize != -1)

    {

        this.progressBar1.Value = (int)(((double)CurrentBytes / (double)FullSize) * 100);        // display total Kbytes and current Kbytes

        label_curr_bytes.Text = CurrentBytes.ToString() + " Kb of " + FullSize.ToString() + " Kb";

    }

if ((Status == DStatus.complete) ||

        (Status == DStatus.failed) ||

        (Status == DStatus.aborted))

        {

            button_start.Enabled = true;

            button_stop.Enabled = false;

        }

    // displaying estimated time left

    label_estimated_time.Text = "Estimated time left";

    string stmp = EstimatedTimeLeft.ToString();

    stmp = stmp.Substring(0, stmp.IndexOf('.'));

    label_estimated_time.Text = "Estimated time left : " + stmp;

}

If required, it can download through the proxy (with user name and password).
The downloading can be aborted at any moment because it runs in the worker thread.

Points of Interest
If the newer version of this component is released, it can be found at www.DotNetRemoting.com
along with other useful classes and components



About this entry