Custom Stream Implementation

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

public bool SomeMethod(Stream stream); 

and this method will basically write binary data to this stream. Therefore, if I call this method as follows:

 var file = System.IO.File.Create("SomeFile.txt"); /* call dll method */ SomeMethod(file); 

then I will basically write the output to this file. In this question, I am writing output to networkStream.

In any case, back to the question . The reason I want to create my own thread is because I would like to know when some events happen. For example, if I create my own stream class as:

 class MyStream : Stream { private long Position; public override int Read(byte[] buffer, int offset, int count) { // implementation goes here /* HERE I COULD CALL A CUSTOM EVENT */ } public override long Seek(long offset, SeekOrigin origin) { // SAME THING I WILL LIKE TO PERFORM AN ACTION IF THIS METHOD IS CALLED! } // etc implement rest of abstract methods.... 

I am writing the output of this stream to the network, so I can slow down if an event occurs. If I have control over the dll, then I would not try to implement this.

I would appreciate it if someone could show me a very simple example of how to implement the abstract methods of the Stream abstract class.

+7
source share
2 answers

The simplest user stream is a stream that wraps another stream (like compression streams). Each method would simply redirect its implementation to an internal thread.

 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; } /// } 

Example usage: functionThatTakesStream(new MyStream(new MemoryStream());

Real code should handle exceptions in operations on the iners stream before / after fire events and correctly handle IDisposable.

+13
source

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

+1
source

All Articles