StreamExtensions.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.IO;
  2. #if NET5_0
  3. using System;
  4. using System.Buffers;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. #endif
  9. namespace Masuit.Tools
  10. {
  11. public static class StreamExtensions
  12. {
  13. /// <summary>
  14. /// 将流转换为内存流
  15. /// </summary>
  16. /// <param name="stream"></param>
  17. /// <returns></returns>
  18. public static MemoryStream SaveAsMemoryStream(this Stream stream)
  19. {
  20. stream.Position = 0;
  21. return new MemoryStream(stream.ToArray());
  22. }
  23. /// <summary>
  24. ///
  25. /// </summary>
  26. /// <param name="stream"></param>
  27. /// <returns></returns>
  28. public static byte[] ToArray(this Stream stream)
  29. {
  30. stream.Position = 0;
  31. byte[] bytes = new byte[stream.Length];
  32. stream.Read(bytes, 0, bytes.Length);
  33. // 设置当前流的位置为流的开始
  34. stream.Seek(0, SeekOrigin.Begin);
  35. return bytes;
  36. }
  37. #if NET5_0
  38. /// <summary>
  39. ///
  40. /// </summary>
  41. /// <param name="stream"></param>
  42. /// <param name="cancellationToken"></param>
  43. /// <returns></returns>
  44. public static async Task<byte[]> ToArrayAsync(this Stream stream, CancellationToken cancellationToken = default)
  45. {
  46. byte[] bytes = new byte[stream.Length];
  47. await stream.ReadAsync(bytes, cancellationToken);
  48. stream.Seek(0, SeekOrigin.Begin);// 设置当前流的位置为流的开始
  49. return bytes;
  50. }
  51. #endif
  52. }
  53. }