Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22824

Streams implementation in C#

What do I have to do to implement my own stream, which uses custom compression routine, similiar to, for example, GZipStream?

I obviously have to subclass the Stream class, but which methods should be implemented by me and which methods can be left with their default implementations?

Basically speaking, there is a special part of documentation, but maybe there is a better and easier option?

Notes to Implementers

When implementing a derived class of Stream, you must provide implementations for the Read and Write methods. The asynchronous methods BeginRead, EndRead, BeginWrite, and EndWrite are implemented through the synchronous methods Read and Write. Similarly, your implementations of Read and Write will work correctly with the asynchronous methods. The default implementations of ReadByte and WriteByte create a new single-element byte array, and then call your implementations of Read and Write. When deriving from Stream, if you have an internal byte buffer, it is strongly recommended that you override these methods to access your internal buffer for substantially better performance. You must also provide implementations of CanRead, CanSeek, CanWrite, Flush, Length, Position, Seek, and SetLength.

Do not override the Close method, instead, put all of the Stream cleanup logic in the Dispose method. For more information, see Implementing a Dispose Method.

Upvotes: 3

Views: 5376

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063338

The methods you must override are abstract. It will not compile until you have implemented them all. However, you are allowed to throw a NotSupportedException, for example if you return false for CanSeek, then Seek() is allowed to throw. Likewise if your stream is read-only (reports false for CanWrite) then it can throw from Write.

In reality, for a complex case like this, I expect you'll end up overriding most of the (non-async) API.

Upvotes: 5

Related Questions