UploadFileHelper.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace WebAPIBase.Utils
  8. {
  9. public class UploadFileHelper
  10. {
  11. /// <summary>
  12. /// 流文件到字节的转变
  13. /// </summary>
  14. /// <param name="stream"></param>
  15. /// <returns></returns>
  16. public static byte[] StreamToBytes(Stream stream)
  17. {
  18. byte[] bytes = new byte[stream.Length];
  19. stream.Read(bytes, 0, bytes.Length);
  20. // 设置当前流的位置为流的开始
  21. stream.Seek(0, SeekOrigin.Begin);
  22. return bytes;
  23. }
  24. /// <summary>
  25. /// 字节到流文件的转变
  26. /// </summary>
  27. /// <param name="bytes"></param>
  28. /// <returns></returns>
  29. public static Stream BytesToStream(byte[] bytes)
  30. {
  31. Stream stream = new MemoryStream(bytes);
  32. return stream;
  33. }
  34. /// <summary>
  35. /// 流文件转换为文件存入磁盘
  36. /// </summary>
  37. /// <param name="stream"></param>
  38. /// <param name="fileName"></param>
  39. public static void StreamToFile(Stream stream, string fileName)
  40. {
  41. // 把 Stream 转换成 byte[]
  42. byte[] bytes = new byte[stream.Length];
  43. stream.Read(bytes, 0, bytes.Length);
  44. // 设置当前流的位置为流的开始
  45. stream.Seek(0, SeekOrigin.Begin);
  46. // 把 byte[] 写入文件
  47. FileStream fs = new FileStream(fileName, FileMode.Create);
  48. BinaryWriter bw = new BinaryWriter(fs);
  49. bw.Write(bytes);
  50. bw.Close();
  51. fs.Close();
  52. }
  53. /// <summary>
  54. /// 文件读取成stream
  55. /// </summary>
  56. /// <param name="fileName"></param>
  57. /// <returns></returns>
  58. public static Stream FileToStream(string fileName)
  59. {
  60. // 打开文件
  61. FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
  62. // 读取文件的 byte[]
  63. byte[] bytes = new byte[fileStream.Length];
  64. fileStream.Read(bytes, 0, bytes.Length);
  65. fileStream.Close();
  66. // 把 byte[] 转换成 Stream
  67. Stream stream = new MemoryStream(bytes);
  68. return stream;
  69. }
  70. }
  71. }