StreamHelper.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.IO;
  2. using System.Threading;
  3. using System;
  4. using System.Threading.Tasks;
  5. namespace MediaBrowser.Controller.IO
  6. {
  7. public static class StreamHelper
  8. {
  9. public static void CopyTo(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken)
  10. {
  11. byte[] buffer = new byte[bufferSize];
  12. int read;
  13. while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
  14. {
  15. cancellationToken.ThrowIfCancellationRequested();
  16. destination.Write(buffer, 0, read);
  17. if (onStarted != null)
  18. {
  19. onStarted();
  20. onStarted = null;
  21. }
  22. }
  23. }
  24. public static async Task CopyToAsync(Stream source, Stream destination, int bufferSize, IProgress<double> progress, long contentLength, CancellationToken cancellationToken)
  25. {
  26. byte[] buffer = new byte[bufferSize];
  27. int read;
  28. long totalRead = 0;
  29. while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
  30. {
  31. cancellationToken.ThrowIfCancellationRequested();
  32. destination.Write(buffer, 0, read);
  33. totalRead += read;
  34. double pct = totalRead;
  35. pct /= contentLength;
  36. pct *= 100;
  37. progress.Report(pct);
  38. }
  39. }
  40. }
  41. }