using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using System.Threading; namespace WebRequestSample { public partial class Form1 : Form { private Thread thrDownload; private Stream strResponse; private Stream strLocal; private HttpWebRequest webRequest; private HttpWebResponse webResponse; private static int PercentProgress; private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes); public Form1() { InitializeComponent(); } //WebClient client = new WebClient(); //Uri siteUri = null; private void DownloadButton_Click(object sender, EventArgs e) { if ((URLTextBox.Text.IndexOf("http://")) == -1) MessageBox.Show("Invalid URL"); else { saveFileDialog1.OverwritePrompt = true; saveFileDialog1.FileName = "Enter File Name"; DialogResult result = saveFileDialog1.ShowDialog(); if (result == DialogResult.OK) { ProgressLabel.Text = "Download Starting"; thrDownload = new Thread(new ThreadStart(Download)); thrDownload.Start(); } } } private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes) { PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes); DownloadProgressBar.Value = PercentProgress; ProgressLabel.Text = "Downloaded " + BytesRead + " out of " + TotalBytes + " (" + PercentProgress + "%)"; } private void Download() { using (WebClient wcDownload = new WebClient()) { try { webRequest = (HttpWebRequest)WebRequest.Create(URLTextBox.Text); webRequest.Credentials = CredentialCache.DefaultCredentials; webResponse = (HttpWebResponse)webRequest.GetResponse(); Int64 fileSize = webResponse.ContentLength; strResponse = wcDownload.OpenRead(URLTextBox.Text); strLocal = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.None); int byteSize = 0; byte[] downloadBuffer = new byte[2048]; while ((byteSize = strResponse.Read(downloadBuffer, 0, downloadBuffer.Length)) > 0) { strLocal.Write(downloadBuffer, 0, byteSize); this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length,fileSize}); } } finally { strResponse.Close(); strLocal.Close(); } } } private void StopButton_Click(object sender, EventArgs e) { ProgressLabel.Text = "Download Stopped"; webResponse.Close(); strResponse.Close(); strLocal.Close(); // Abort the thread that's downloading thrDownload.Abort(); // Set the progress bar back to 0 and the label DownloadProgressBar.Value = 0; } } }