I need to craft a Stream
that will only support Read()
operation - the stream will be readonly and non-seekable. Still I have to implement a lot of properties such as Position
(which will throw a NotImplementedException
) - that's a lot of boilerplate code.
Is there perhaps some standard implementation for such stream where I only need to override
the Read()
operation?
A Stream has one other read and write mechanism designed to read or write a single byte. When a ReadByte method is called, the byte value at the current position is returned and the position of the Stream is advanced forward one place.
Every .NET developer should have a complete understanding of how streams work and how those streams can be leveraged to maximize software development efficiency. The Stream class in .NET is an abstract class that is located in the System.IO namespace. As the Stream class uses an "abstract" modifier, the class is considered incomplete.
A Microsoft Stream base class includes the BeginRead and BeginWrite methods for asynchronous functionality. Asynchronous usage is often considered "advanced" functionality. While an in-depth discussion of asynchronous programming and the use of delegates are beyond the scope of this article, a basic description of asynchronous usage is appropriate.
Reading is defined as transferring data from the Stream to another location such as a byte array or any other construct that can hold data. The second operation is writing. This operation describes the movement of data from some data source such as a byte array to the Stream.
You can use the constructor new MemorySream(byte[] buffer, bool writeable)
(documentation).
Setting the writeable
parameter to false
will make the stream readonly.
Such a stream does not exist in the BCL. You have to write it. In my life I have implemented about a dozen such streams and it is not too bad. The 2nd one is much easier because you can use the first one as a template.
I recommend that you inherit from Stream
and not from some other stream. If you were inheriting from MemoryStream
you'd abuse inheritance to save code which is not its primary purpose. Your derived stream would not work like a MemoryStream
and it is-not a MemoryStream
.
Prefer composition over inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With