StreamWrap.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.IO;
  3. namespace SmbSvr.Ramfs.Inters
  4. {
  5. public class StreamWrap : Stream
  6. {
  7. private readonly MemoryStream _underlyingStream;
  8. private long _pos;
  9. public event EventHandler Closed;
  10. public StreamWrap(MemoryStream stream)
  11. {
  12. _underlyingStream = stream;
  13. }
  14. public override void Flush() => _underlyingStream.Flush();
  15. public override long Seek(long offset, SeekOrigin origin)
  16. {
  17. switch (origin)
  18. {
  19. case SeekOrigin.Begin:
  20. _pos = offset;
  21. break;
  22. case SeekOrigin.Current:
  23. _pos += offset;
  24. break;
  25. case SeekOrigin.End:
  26. _pos = Length + offset;
  27. break;
  28. default:
  29. throw new ArgumentOutOfRangeException(nameof(origin), origin, null);
  30. }
  31. return _pos;
  32. }
  33. public override void SetLength(long value)
  34. {
  35. lock (_underlyingStream)
  36. _underlyingStream.SetLength(value);
  37. }
  38. public override int Read(byte[] buffer, int offset, int count)
  39. {
  40. lock (_underlyingStream)
  41. {
  42. try
  43. {
  44. _underlyingStream.Position = _pos;
  45. return _underlyingStream.Read(buffer, offset, count);
  46. }
  47. finally
  48. {
  49. _pos = _underlyingStream.Position;
  50. }
  51. }
  52. }
  53. public override void Write(byte[] buffer, int offset, int count)
  54. {
  55. lock (_underlyingStream)
  56. {
  57. _underlyingStream.Position = _pos;
  58. _underlyingStream.Write(buffer, offset, count);
  59. _pos = _underlyingStream.Position;
  60. }
  61. }
  62. public override bool CanRead => _underlyingStream.CanRead;
  63. public override bool CanSeek => _underlyingStream.CanSeek;
  64. public override bool CanWrite => _underlyingStream.CanWrite;
  65. public override long Length => _underlyingStream.Length;
  66. public override long Position { get => _pos; set => _pos = value; }
  67. public override void Close()
  68. {
  69. OnClosed();
  70. }
  71. protected virtual void OnClosed()
  72. {
  73. Closed?.Invoke(this, EventArgs.Empty);
  74. }
  75. }
  76. }