I want to write a String to a Stream (a MemoryStream in this case) and read the bytes one by one.
stringAsStream = new MemoryStream();
UnicodeEncoding uniEncoding = new UnicodeEncoding();
String message = "Message";
stringAsStream.Write(uniEncoding.GetBytes(message), 0, message.Length);
Console.WriteLine("This:\t\t" + (char)uniEncoding.GetBytes(message)[0]);
Console.WriteLine("Differs from:\t" + (char)stringAsStream.ReadByte());
The (undesired) result I get is:
This: M
Differs from: ?
It looks like it's not being read correctly, as the first char of "Message" is 'M', which works when getting the bytes from the UnicodeEncoding instance but not when reading them back from the stream.
What am I doing wrong?
The bigger picture: I have an algorithm which will work on the bytes of a Stream, I'd like to be as general as possible and work with any Stream. I'd like to convert an ASCII-String into a MemoryStream, or maybe use another method to be able to work on the String as a Stream. The algorithm in question will work on the bytes of the Stream.
Best Answer
After you write to the
MemoryStream
and before you read it back, you need toSeek
back to the beginning of theMemoryStream
so you're not reading from the end.UPDATE
After seeing your update, I think there's a more reliable way to build the stream:
As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the
MemoryStream
. This takes the hassle out of ensuring the entire byte array for the string is written.Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.