FileHelp.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Security.Policy;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Ropin.Inspection.Common.Helper
  10. {
  11. public static class FileHelp
  12. {
  13. /// <summary>
  14. /// 下载视频
  15. /// </summary>
  16. /// <param name="pathUrl">下载地址</param>
  17. /// <param name="path">保存路径</param>
  18. public static void DownLoadVideo(string pathUrl,string path)
  19. {
  20. System.Net.HttpWebRequest request = null;
  21. System.Net.HttpWebResponse response = null;
  22. //请求网络路径地址
  23. request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pathUrl);
  24. request.Timeout = 5000; // 超时时间
  25. //获得请求结果
  26. response = (System.Net.HttpWebResponse)request.GetResponse();
  27. Stream stream = response.GetResponseStream();
  28. //先创建文件
  29. Stream sos = new System.IO.FileStream(path, System.IO.FileMode.Create);
  30. byte[] img = new byte[1024];
  31. int total = stream.Read(img, 0, img.Length);
  32. while (total > 0)
  33. {
  34. //之后再输出内容
  35. sos.Write(img, 0, total);
  36. total = stream.Read(img, 0, img.Length);
  37. }
  38. stream.Close();
  39. stream.Dispose();
  40. sos.Close();
  41. sos.Dispose();
  42. }
  43. #region 文件下载
  44. public static bool FilesDown(string Url,string pathFile)
  45. {
  46. try
  47. {
  48. WriteBytesToFile(pathFile, GetBytesFromUrl(Url));
  49. return true;
  50. }
  51. catch (Exception ex)
  52. {
  53. return false;
  54. }
  55. }
  56. private static byte[] GetBytesFromUrl(string url)
  57. {
  58. byte[] b;
  59. HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
  60. WebResponse myResp = myReq.GetResponse();
  61. Stream stream = myResp.GetResponseStream();
  62. using (BinaryReader br = new BinaryReader(stream))
  63. {
  64. b = br.ReadBytes(500000);
  65. br.Close();
  66. }
  67. myResp.Close();
  68. return b;
  69. }
  70. private static void WriteBytesToFile(string fileName, byte[] content)
  71. {
  72. FileStream fs = new FileStream(fileName, FileMode.Create);
  73. BinaryWriter w = new BinaryWriter(fs);
  74. try
  75. {
  76. w.Write(content);
  77. }
  78. finally
  79. {
  80. fs.Close();
  81. w.Close();
  82. }
  83. }
  84. #endregion
  85. }
  86. }