【2】下载文件【Http通信】
/// <summary> ///下载方法(带进度条) /// </summary> /// <param name="URL">服务器URL地址</param> /// <param name="Filename">存放到本地的路径</param> /// <param name="Prog">进度条</param> public string DownCategoryFile(string URL, string Filename, ProgressBar Prog) { try { HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.Create(URL); HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; Prog.Maximum = (int)totalBytes; Stream st = myrp.GetResponseStream(); Stream so = new FileStream(Filename, 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; Application.DoEvents(); so.Write(by, 0, osize); Prog.Value = (int)totalDownloadedByte; osize = st.Read(by, 0, (int)by.Length); } so.Close(); st.Close(); return "下载成功"; //MessageBox.Show("更新完毕!", "提示:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1); } catch { return "下载失败"; } } |