You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.8 KiB

  1. using Apewer;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text;
  6. namespace Apewer.Internals
  7. {
  8. internal class StreamHelper
  9. {
  10. public static void Dispose(Stream stream, bool flush = false, bool close = true)
  11. {
  12. if (stream != null)
  13. {
  14. try { if (flush) stream.Flush(); } catch { }
  15. try { if (close) stream.Close(); } catch { }
  16. try { stream.Dispose(); } catch { }
  17. }
  18. }
  19. public static bool ResetPosition(Stream stream)
  20. {
  21. if (stream == null) return false;
  22. try
  23. {
  24. stream.Position = 0;
  25. if (stream.CanSeek) stream.Seek(0, SeekOrigin.Begin);
  26. return true;
  27. }
  28. catch
  29. {
  30. return false;
  31. }
  32. }
  33. public static long Read(Stream source, Stream destination, int argBuffer = Constant.DefaultBufferCapacity, Action<Int64> progress = null)
  34. {
  35. if (source == null) return 0;
  36. if (destination == null) return 0;
  37. if (!source.CanRead) return 0;
  38. if (!destination.CanWrite) return 0;
  39. if (argBuffer < 1) return 0;
  40. long result = 0;
  41. var failed = false;
  42. var callback = progress != null;
  43. var count = 0;
  44. while (true)
  45. {
  46. count = 0;
  47. var buffer = new byte[argBuffer];
  48. try { count = source.Read(buffer, 0, buffer.Length); } catch { failed = true; }
  49. if (failed) break;
  50. if (callback) progress(result);
  51. if (count == 0) break;
  52. try { destination.Write(buffer, 0, count); } catch { failed = true; }
  53. if (failed) break;
  54. result += count;
  55. }
  56. return result;
  57. }
  58. public static byte[] Read(Stream argSource, int argBuffer = Constant.DefaultBufferCapacity, Action<Int64> argCallback = null)
  59. {
  60. var memory = new MemoryStream();
  61. Read(argSource, memory, argBuffer, argCallback);
  62. var result = memory.ToArray();
  63. Dispose(memory);
  64. return result;
  65. }
  66. public static long Read(IEnumerable<Stream> argSource, Stream argDestination, bool argDispose = false, int argBuffer = Constant.DefaultBufferCapacity, Action<Int64> argCallback = null)
  67. {
  68. var result = 0L;
  69. if (argSource != null)
  70. {
  71. foreach (var source in argSource)
  72. {
  73. var count = Read(source, argDestination, argBuffer, argCallback);
  74. if (argDispose) Dispose(source);
  75. result += count;
  76. }
  77. }
  78. return result;
  79. }
  80. }
  81. }