Implement custom stream

后端 未结 2 1151
一个人的身影
一个人的身影 2021-01-04 10:08

I am calling a dll that writes to a stream. The signature of the method in the dll looks like:

public bool SomeMethod(Stream stream);

and t

2条回答
  •  孤城傲影
    2021-01-04 10:38

    The easiest custom stream a stream that "wraps" some other stream (similar to compression streams). Each method would simply redirect its implementation to internal stream.

    class MyStream : Stream
    {
     Stream inner;
     public MyStream(Stream inner)
     {
      this.inner = inner;
     }
    
     public override int Read(byte[] buffer, int offset, int count) 
     { 
        var result = inner.Read(buffer, offset, count);
    
                /* HERE I COULD CALL A CUSTOM EVENT */ 
       return result;
     } 
    ///
    }
    

    Usage sample: functionThatTakesStream(new MyStream(new MemoryStream());.

    Real code will need to handle exceptions in operations on inners stream before/after fireing events and deal with IDisposable correctly.

提交回复
热议问题