StreamExtensions.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.IO;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace Ips.Library.Basic
  5. {
  6. public static class StreamExtensions
  7. {
  8. public static byte[] GetAllBytes(this Stream stream)
  9. {
  10. using (var memoryStream = new MemoryStream())
  11. {
  12. if (stream.CanSeek)
  13. {
  14. stream.Position = 0;
  15. }
  16. stream.CopyTo(memoryStream);
  17. return memoryStream.ToArray();
  18. }
  19. }
  20. public static async Task<byte[]> GetAllBytesAsync(this Stream stream, CancellationToken cancellationToken = default)
  21. {
  22. using (var memoryStream = new MemoryStream())
  23. {
  24. if (stream.CanSeek)
  25. {
  26. stream.Position = 0;
  27. }
  28. await stream.CopyToAsync(memoryStream, cancellationToken);
  29. return memoryStream.ToArray();
  30. }
  31. }
  32. public static Task CopyToAsync(this Stream stream, Stream destination, CancellationToken cancellationToken)
  33. {
  34. if (stream.CanSeek)
  35. {
  36. stream.Position = 0;
  37. }
  38. return stream.CopyToAsync(
  39. destination,
  40. 81920, //this is already the default value, but needed to set to be able to pass the cancellationToken
  41. cancellationToken
  42. );
  43. }
  44. }
  45. }