日期:2014-05-18 浏览次数:21178 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using System.Threading; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// 更新进度条委托 /// </summary> /// <param name="strValue"></param> delegate void UpdateInfo(int strValue); private void button1_Click(object sender, EventArgs e) { if (txtDown.Text.Trim() == String.Empty) { return; } #region 通过请求字节数获取进度条最大值 HttpWebRequest MyReq = (HttpWebRequest)HttpWebRequest.Create(txtDown.Text.Trim()); HttpWebResponse MyRes = (HttpWebResponse)MyReq.GetResponse(); progressBar1.Maximum = (int)MyRes.ContentLength / 1024+1; #endregion #region 获取下载地址的文件名 string[] DownUrl = txtDown.Text.Trim().Split('/'); string cFileName = DownUrl[DownUrl.Length - 1]; string cFileName_Remove = ""; if (cFileName.Contains("?")) { cFileName_Remove = cFileName.Remove(cFileName.IndexOf("?")); saveFileDialog1.FileName = cFileName_Remove; } else { saveFileDialog1.FileName = cFileName; } #endregion //打开保存对话框 saveFileDialog1.ShowDialog(); #region 启动下载线程 if (saveFileDialog1.FileName != String.Empty) { Thread tUpdatelabel = new Thread(new ThreadStart(DownFile));//线程控制 tUpdatelabel.Start(); } #endregion } /// <summary> /// 下载 /// </summary> private void DownFile() { HttpWebRequest MyReq = (HttpWebRequest)HttpWebRequest.Create(txtDown.Text.Trim()); HttpWebResponse MyRes = (HttpWebResponse)MyReq.GetResponse(); if (MyRes.ContentLength > 0) { Stream stream_Url = MyRes.GetResponseStream(); Stream stream_FileDown = new FileStream(saveFileDialog1.FileName, FileMode.Create); byte[] Mybyte = new byte[1024]; int osize = stream_Url.Read(Mybyte, 0, Mybyte.Length); int i=0; while (osize > 0) { i++; UpdateprogressBar(i); stream_FileDown.Write(Mybyte, 0, Mybyte.Length); osize = stream_Url.Read(Mybyte, 0, (int)Mybyte.Length); } stream_FileDown.Close(); stream_Url.Close(); } MessageBox.Show("下载成功!"); } /// <summary> /// progressBar更新值变化 /// </summary> /// <param name="strValue"></param> private void UpdateprogressBar(int strValue) { Form1 MyForm = this; if (MyForm.InvokeRequired) { UpdateInfo updateInfo = new UpdateInfo(UpdateprogressBar); MyForm.progressBar1.Invoke(updateInfo, new object[] { strValue }); } else { MyForm.progressBar1.Value = strValue; } } } }