How do i convert a memorystream to text?
I am using a tcpstream and copied the data into memorystream. Now i would like to convert it to a text (UTF-8 encoded). I tried various ways and did flush() but i could not figured it out. I tried using it in combination with StreamReader with no luck (i get a empty s开发者_StackOverflow中文版tring).
Just get the data from the MemoryStream
and decode it:
string decoded = Encoding.UTF8.GetString(theMemoryStream.ToArray());
It's likely that you get an empty string because you are reading from the MemoryStream
without resetting it's position. The ToArray
method gets all the data regardless of where the current positon is.
If it happens to be a byte array before you put it in the MemoryStream
, you can just use that directly.
using(MemoryStream ms = GetStream())
using(StreamReader reader = new StreamReader(ms))
{
ms.Position = 0;
Console.WriteLine(reader.ReadToEnd());
}
精彩评论