Search This Blog

Monday, July 6, 2009

C# Download File with Progress Bar

From devtoolshed.com

C# Download File with Progress Bar

Need a Winform with
TextBox - hold URL
Button - Start Download
Progressbar -
BackGroundWorker - Perform the work

Add Using System.IO to module
Set BackGroundWorker to reportProgress=true

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CodeExamples
{
public partial class frmDownload : Form
{
public frmDownload()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string urlstring = this.txtURL.Text;
string filename = string.Format("{0}\\DRC_Update.exe",Environment.CurrentDirectory);

if (urlstring.Length > 0)
{
Uri url = new Uri(urlstring);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();

Int64 iSize = response.ContentLength;
Int64 iRunningByteTotal = 0;

using (System.Net.WebClient client = new System.Net.WebClient())
{
using (System.IO.Stream streamRemote = client.OpenRead(new Uri(urlstring)))
{
using (FileStream streamLocal = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None))
{
int iByteSize = 0;
byte[] byteBuffer = new byte[iSize];
while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{

// write the bytes to the file system at the file path specified
streamLocal.Write(byteBuffer, 0, iByteSize);
iRunningByteTotal += iByteSize;


// calculate the progress out of a base "100"
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)byteBuffer.Length;
double dProgressPercentage = (dIndex / dTotal);
int iProgressPercentage = (int)(dProgressPercentage * 100);


// update the progress bar
backgroundWorker1.ReportProgress(iProgressPercentage);
}
streamLocal.Close();
}
streamRemote.Close();
}

}

}
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("File download complete");
}
}
}