Et eksempel med HTTP download:
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Threading;
public class MainForm : Form
{
private ProgressBar bar;
private Button start;
private Button abort;
private Thread t;
public MainForm()
{
bar = new ProgressBar();
start = new Button();
abort = new Button();
SuspendLayout();
bar.Location = new Point(50, 50);
bar.Size = new Size(200, 50);
bar.Name = "Progress Bar";
start.Location = new Point(50,150);
start.Size = new Size(200, 50);
start.Name = "Start Button";
start.Text = "Start";
start.Click += new EventHandler(StartClick);
abort.Location = new Point(50,250);
abort.Size = new Size(200, 50);
abort.Name = "Abort Button";
abort.Text = "Abort";
abort.Click += new EventHandler(AbortClick);
ClientSize = new Size(300, 350);
Controls.Add(bar);
Controls.Add(start);
Controls.Add(abort);
Name = "Main Form";
Text = "Main Form";
ResumeLayout(false);
}
void Reset(int n)
{
bar.Minimum = 0;
bar.Maximum = n;
bar.Value = 0;
}
void Update(int n)
{
bar.Value = n;
}
delegate void ResetHandler(int n);
delegate void UpdateHandler(int n);
void Copy()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("
http://www.tmk.com/ftp/vms-freeware/fileserv/unzip.zip");
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
int tot = (int)resp.ContentLength;
if(bar.InvokeRequired)
{
bar.Invoke(new ResetHandler(Reset), new object[] { tot });
}
else
{
Reset(tot);
}
Stream f1 = resp.GetResponseStream();
Stream f2 = new FileStream(@"C:\unzip.zip", FileMode.CreateNew, FileAccess.Write);
int sofar = 0;
byte[] b = new byte[1000];
int n;
while((n = f1.Read(b, 0, b.Length)) > 0 )
{
f2.Write(b, 0, n);
sofar += n;
if(bar.InvokeRequired)
{
bar.Invoke(new UpdateHandler(Update), new object[] { sofar });
}
else
{
Update(sofar);
}
}
f2.Close();
f1.Close();
resp.Close();
}
void StartClick(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(Copy));
t.Start();
}
void AbortClick(object sender, EventArgs e)
{
t.Abort();
}
[STAThread]
public static void Main(string[] args)
{
Application.Run(new MainForm());
Application.Exit();
Environment.Exit(0);
}
}