using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Diagnostics; namespace MyDownload { public partial class MyDownload : Form { string Url = ""; //要下载的文件的地址 string filePath = ""; //下载后文件保存地址 //private const string applicationFile = "LMS"; /// /// 构造函数 /// /// /// public MyDownload(string Url, string filePath) { InitializeComponent(); this.label1.Text = ""; this.Url = Url; this.filePath = filePath; } /// /// 清楚已有文件 /// /// private void RemoveSetupFile(string filepath) { try { string folder = new DirectoryInfo(filepath).FullName; //if (File.Exists(folder + @"\" + applicationFile + ".exe")) //{ // File.Delete(folder + @"\" + applicationFile + ".exe"); //} //if (File.Exists(folder + @"\" + applicationFile + ".msi")) //{ // File.Delete(folder + @"\" + applicationFile + ".msi"); //} if(File.Exists(folder)) { File.Delete(folder); } } catch { } } /// /// 下载 /// /// /// private void btnDown_Click(object sender, EventArgs e) { RemoveSetupFile(filePath); DownloadFile(Url, filePath); Process.Start(filePath); Application.Exit(); } /// /// c#,.net 下载文件 /// /// 下载文件地址 /// 下载后的存放地址 /// 用于显示的进度条 public void DownloadFile(string URL, string filename) { float percent = 0; try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; if (prog != null) { prog.Maximum = (int)totalBytes; } System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; System.Windows.Forms.Application.DoEvents(); so.Write(by, 0, osize); if (prog != null) { prog.Value = (int)totalDownloadedByte; } osize = st.Read(by, 0, (int)by.Length); percent = (float)totalDownloadedByte / (float)totalBytes * 100; label1.Text = "当前下载进度" + percent.ToString() + "%"; System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息 } so.Close(); st.Close(); } catch (System.Exception) { throw; } this.Close(); } /// /// 取消 /// /// /// private void btn_Cancel_Click(object sender, EventArgs e) { Process.Start(filePath); Application.Exit(); } } }