WriteOnlyBufferedStream.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.IO;
  3. namespace BestHTTP.Extensions
  4. {
  5. /// <summary>
  6. /// A custom buffer stream implementation that will not close the underlying stream.
  7. /// </summary>
  8. public sealed class WriteOnlyBufferedStream : Stream
  9. {
  10. public override bool CanRead { get { return false; } }
  11. public override bool CanSeek { get { return false; } }
  12. public override bool CanWrite { get { return true; } }
  13. public override long Length { get { return this.buffer.Length; } }
  14. public override long Position { get { return this._position; } set { throw new NotImplementedException("Position set"); } }
  15. private int _position;
  16. private byte[] buffer;
  17. private Stream stream;
  18. public WriteOnlyBufferedStream(Stream stream, int bufferSize)
  19. {
  20. this.stream = stream;
  21. this.buffer = new byte[bufferSize];
  22. this._position = 0;
  23. }
  24. public override void Flush()
  25. {
  26. if (this._position > 0)
  27. {
  28. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  29. HTTPManager.Logger.Information("BufferStream", string.Format("Flushing {0:N0} bytes", this._position));
  30. this.stream.Write(this.buffer, 0, this._position);
  31. this._position = 0;
  32. }
  33. }
  34. public override void Write(byte[] bufferFrom, int offset, int count)
  35. {
  36. while (count > 0)
  37. {
  38. int writeCount = Math.Min(count, this.buffer.Length - this._position);
  39. Array.Copy(bufferFrom, offset, this.buffer, this._position, writeCount);
  40. this._position += writeCount;
  41. offset += writeCount;
  42. count -= writeCount;
  43. if (this._position == this.buffer.Length)
  44. this.Flush();
  45. }
  46. }
  47. public override int Read(byte[] buffer, int offset, int count)
  48. {
  49. return 0;
  50. }
  51. public override long Seek(long offset, SeekOrigin origin)
  52. {
  53. return 0;
  54. }
  55. public override void SetLength(long value) { }
  56. }
  57. }