In this example from MS, you'll notice that after we read a byte from memory stream, it goes into an int which must then be converted to byte. It stikes me as strange that a function like .ReadByte()
doesn't return a byte in the first place. Is there a reason why MS did it this way?
// Read the remaining bytes, byte by byte.
while(count < memStream.Length)
{
byteArray[count++] =
Convert.ToByte(memStream.ReadByte());
}
a thought occured to me. Perhaps this comes down to usage. Perhaps ReadByte()
is often used to retrieve short lengths, which subsequents get consumed in the retrieve via length variety
int length=ms.ReadByte();
ms.Read(buf,0,lenth);
i.e. you can use the length without a cast. Is this a good enough reason?
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.
You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string. You would not use a Stream in and of itself, but rather use it for polymorphism, i.e. passing it to methods that can accept any implementation of Stream as an argument.
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.
The MemoryStream is one of the basic Stream classes which you'll see used quite a bit. It deals with data directly in memory, as the name implies and its often used to deal with bytes coming from another place, e.g. a file or a network location, without locking the source.
This is not specific to Memory stream, rather it is because of the design of base class "Stream" and the reason for that is
Return value:
The unsigned byte cast to an Int32, or -1 if at the end of the stream.
-1 cannot be represented using unsigned byte
When you use ReadByte
If the read is successful then the current position within the stream is advanced by one byte. but its designed to return -1 if the end of the stream has been reached.
Now this would not be a valid value for Byte
(its unsigned)
ms.Read(buf,0,lenth);
here lenth is the number of bytes to read from the stream and what you get from ReadByte
is first byte its not be used in the this fashion, something like
byte[] buff = new byte[ms.Length];
ms.Read(buff , 0, buff .Length);
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