You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.8 KiB

3 weeks ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace UpdateServiceLibrary.Helper
  5. {
  6. public class DownLoadFileHelper
  7. {
  8. public long TotalSize = 0;
  9. public long DownloadedSize = 0;
  10. public int buffSize = 1024;
  11. public Action<long, long> DownloadStatus;
  12. public ResultModel<Exception> DownloadFile(string URL, string filename)
  13. {
  14. ResultModel<Exception> result = new ResultModel<Exception> { IsSuccess= true };
  15. try
  16. {
  17. System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
  18. System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
  19. TotalSize = myrp.ContentLength;
  20. if (DownloadStatus != null)
  21. DownloadStatus(TotalSize, DownloadedSize);
  22. System.IO.Stream st = myrp.GetResponseStream();
  23. System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
  24. byte[] by = new byte[buffSize];
  25. int osize = st.Read(by, 0, (int)by.Length);
  26. while (osize > 0)
  27. {
  28. DownloadedSize += osize;
  29. if (DownloadStatus != null)
  30. DownloadStatus(TotalSize, DownloadedSize);
  31. so.Write(by, 0, osize);
  32. osize = st.Read(by, 0, (int)by.Length);
  33. }
  34. so.Close();
  35. st.Close();
  36. myrp.Close();
  37. Myrq.Abort();
  38. }
  39. catch (System.Exception e)
  40. {
  41. result.IsSuccess = false;
  42. result.Data = e;
  43. }
  44. return result;
  45. }
  46. }
  47. }