参考网上一位朋友代码,略有修改
1 private System.Threading.Thread thread1; 2 3 public Login() 4 { 5 InitializeComponent(); 6 7 } 8 9 private void button2_Click(object sender, EventArgs e) 10 { 11 thread1 = new System.Threading.Thread(new System.Threading.ThreadStart(UploadVserion)); 12 thread1.Start(); 13 } 14 15 16 private void UploadVserion() 17 { 18 CheckForIllegalCrossThreadCalls = false; 19 20 String url = "http://123.4.5.5/WebApplication/"; 21 String[] arr_file = { "1.exe", "1.dll", "1.png", "1.rar", "2.mp3" }; 22 23 try 24 { 25 26 foreach (String filename in arr_file) 27 { 28 //DownloadFile("http://localhost:1928/WebServer/downloader/123.rar", @"C:\123.rar", progressBar1, label1); 29 30 String fullpath = url + filename; 31 String savepath = Application.StartupPath +"\\" + filename; 32 this.label3.Text = "更新文件:" + filename; 33 DownloadFile(fullpath, savepath, this.progressBar1, label4); 34 } 35 36 this.label3.Text = "更新成功"; 37 38 } 39 catch (System.Exception ex) 40 { 41 this.label3.Text = ex.Message ; 42 } 43 } 44 45 /// <summary> 46 /// c#,.net 下载文件 47 /// </summary> 48 /// <param name="URL">下载文件地址</param> 49 /// <param name="URL">下载文件地址</param> 50 /// <param name="Filename">下载后的存放地址</param> 51 /// <param name="Prog">用于显示的进度条</param> 52 /// 53 private void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1) 54 { 55 decimal percent = 0; 56 try 57 { 58 System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); 59 System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); 60 long totalBytes = myrp.ContentLength; 61 if (prog != null) 62 { 63 prog.Maximum = (int)totalBytes; 64 } 65 System.IO.Stream st = myrp.GetResponseStream(); 66 System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); 67 long totalDownloadedByte = 0; 68 byte[] by = new byte[1024]; 69 int osize = st.Read(by, 0, (int)by.Length); 70 while (osize > 0) 71 { 72 totalDownloadedByte = osize + totalDownloadedByte; 73 System.Windows.Forms.Application.DoEvents(); 74 so.Write(by, 0, osize); 75 if (prog != null) 76 { 77 prog.Value = (int)totalDownloadedByte; 78 } 79 osize = st.Read(by, 0, (int)by.Length); 80 81 percent = Math.Round((decimal)totalDownloadedByte / (decimal)totalBytes * 100, 2); 82 label4.Text = "当前补丁下载进度" + percent.ToString() + "%"; 83 System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息 84 } 85 so.Close(); 86 st.Close(); 87 } 88 catch (System.Exception ex) 89 { 90 String a = ex.Message; 91 throw; 92 } 93 } 94 95 private void button3_Click(object sender, EventArgs e) 96 { 97 DialogResult result = MessageBox.Show("确认取消更新?", "提示···", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); 98 if (result == DialogResult.OK) 99 { 100 //thread1.Interrupt(); 101 102 //this.label4.Text = "1"; 103 thread1.Abort(); 104 thread1.Join(); 105 106 } 107 }