using System; using System.Collections.Generic; using System.Text; namespace UpdateServiceLibrary.Helper { public class DownLoadFileHelper { public long TotalSize = 0; public long DownloadedSize = 0; public int buffSize = 1024; public Action DownloadStatus; public ResultModel DownloadFile(string URL, string filename) { ResultModel result = new ResultModel { IsSuccess= true }; try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); TotalSize = myrp.ContentLength; if (DownloadStatus != null) DownloadStatus(TotalSize, DownloadedSize); System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); byte[] by = new byte[buffSize]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { DownloadedSize += osize; if (DownloadStatus != null) DownloadStatus(TotalSize, DownloadedSize); so.Write(by, 0, osize); osize = st.Read(by, 0, (int)by.Length); } so.Close(); st.Close(); myrp.Close(); Myrq.Abort(); } catch (System.Exception e) { result.IsSuccess = false; result.Data = e; } return result; } } }