Writing String to Stream and reading it back does not work

后端 未结 5 1068
死守一世寂寞
死守一世寂寞 2020-12-30 18:54

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 uniEn         


        
5条回答
  •  执念已碎
    2020-12-30 19:54

    You're using message.Length which returns the number of characters in the string, but you should be using the nubmer of bytes to read. You should use something like:

    byte[] messageBytes = uniEncoding.GetBytes(message);
    stringAsStream.Write(messageBytes, 0, messageBytes.Length);
    

    You're then reading a single byte and expecting to get a character from it just by casting to char. UnicodeEncoding will use two bytes per character.

    As Justin says you're also not seeking back to the beginning of the stream.

    Basically I'm afraid pretty much everything is wrong here. Please give us the bigger picture and we can help you work out what you should really be doing. Using a StreamWriter to write and then a StreamReader to read is quite possibly what you want, but we can't really tell from just the brief bit of code you've shown.

提交回复
热议问题