Implement custom stream

后端 未结 2 1150
一个人的身影
一个人的身影 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:20

    If all you want to do is fire an event when Read, Seek or similar methods are called, override the base class versions, call them directly and raise the appropriate event before or after. If you want help on writing stream classes, have a look at the .Net code itself available at http://referencesource.microsoft.com/netframework.aspx. However, if you want to parse the stream in to something more readable, consider creating an IEnumerable<MyClass> that reads in and processes the stream, instead.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题