Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a default implementation for a readonly stream in .NET?

Tags:

c#

.net

stream

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?

like image 772
sharptooth Avatar asked Apr 03 '14 09:04

sharptooth


People also ask

How does a single byte read and write in a stream?

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.

What should every developer know about streams?

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.

What is the beginread and beginwrite method in stream?

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.

What is reading and writing in Java streams?

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.


2 Answers

You can use the constructor new MemorySream(byte[] buffer, bool writeable) (documentation).

Setting the writeable parameter to false will make the stream readonly.

like image 139
Andre Soares Avatar answered Sep 29 '22 11:09

Andre Soares


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.

like image 20
usr Avatar answered Sep 29 '22 12:09

usr