StreamPollyfill.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.IO;
  3. namespace Agent.Polyfills
  4. {
  5. /// <summary>
  6. /// .NET 4.0부터 지원하는 Stream의 [CopyTo] 메서드 구현
  7. /// </summary>
  8. static class StreamPollyfill
  9. {
  10. const int DefaultBufferSize = 4096;
  11. public static long CopyTo(this Stream source, Stream destination)
  12. {
  13. return CopyTo(source, destination, DefaultBufferSize, _ => { });
  14. }
  15. public static long CopyTo(this Stream source, Stream destination, int bufferSize)
  16. {
  17. return CopyTo(source, destination, bufferSize, _ => { });
  18. }
  19. public static long CopyTo(this Stream source, Stream destination, Action<long> reportProgress)
  20. {
  21. return CopyTo(source, destination, DefaultBufferSize, reportProgress);
  22. }
  23. public static long CopyTo(this Stream source, Stream destination, int bufferSize, Action<long> reportProgress)
  24. {
  25. if (source == null) throw new ArgumentNullException("source");
  26. if (destination == null) throw new ArgumentNullException("destination");
  27. if (reportProgress == null) throw new ArgumentNullException("reportProgress");
  28. var buffer = new byte[bufferSize];
  29. var transferredBytes = 0L;
  30. for (var bytesRead = source.Read(buffer, 0, buffer.Length); bytesRead > 0; bytesRead = source.Read(buffer, 0, buffer.Length))
  31. {
  32. transferredBytes += bytesRead;
  33. reportProgress(transferredBytes);
  34. destination.Write(buffer, 0, bytesRead);
  35. }
  36. destination.Flush();
  37. return transferredBytes;
  38. }
  39. }
  40. }