What is the main difference between Stream
and MemoryStream
in C#?
If I need to create a Stream
without a file shall I use a MemoryStream
instead?
MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.
The MemoryStream class creates streams that have memory as a backing store instead of a disk or a network connection. MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a MemoryStream object, or the array can be created as empty.
This code shows how to use MemoryStream class and its member to read data in memory stream, which can be used to save it from there. int count; //GetByteData function to get Byte data like if you fetch Image column data from sqlserver or somewhere. byte[] byteArray = getByteData();
The major difference between these is that the input/output stream classes read/write byte stream data. Whereas the Reader/Writer classes handle characters. The methods of input/output stream classes accept byte array as parameter whereas the Reader/Writer classes accept character array as parameter.
MemoryStream
derives from the general class Stream
.
About Stream
from MSDN:
Provides a generic view of a sequence of bytes. This is an abstract class.
So you can't create an instance of Stream
. You have to use one of the derived classes, like MemoryStream
, FileStream
, etc.
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