IOUtils.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright (C) Alibaba Cloud Computing
  3. * All rights reserved.
  4. *
  5. * 版权所有 (C)阿里云计算有限公司
  6. */
  7. using System.IO;
  8. namespace Aliyun.OSS.Util
  9. {
  10. internal static class IoUtils
  11. {
  12. private const int BufferSize = 4 * 1024;
  13. public static void WriteTo(Stream src, Stream dest)
  14. {
  15. var buffer = new byte[BufferSize];
  16. int bytesRead;
  17. while((bytesRead = src.Read(buffer, 0, buffer.Length)) > 0)
  18. {
  19. dest.Write(buffer, 0, bytesRead);
  20. }
  21. dest.Flush();
  22. }
  23. public static long WriteTo(Stream orignStream, Stream destStream, long totalSize)
  24. {
  25. var buffer = new byte[BufferSize];
  26. long alreadyRead = 0;
  27. while (alreadyRead < totalSize)
  28. {
  29. var readSize = orignStream.Read(buffer, 0, BufferSize);
  30. if (readSize <= 0)
  31. break;
  32. if (alreadyRead + readSize > totalSize)
  33. readSize = (int) (totalSize - alreadyRead);
  34. alreadyRead += readSize;
  35. destStream.Write(buffer, 0, readSize);
  36. }
  37. destStream.Flush();
  38. return alreadyRead;
  39. }
  40. }
  41. }