tags:

views:

33

answers:

2

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 string).

+2  A: 
using(MemoryStream ms = GetStream())
using(StreamReader reader = new StreamReader(ms))
{
    ms.Position = 0;
    Console.WriteLine(reader.ReadToEnd());
}
Yuriy Faktorovich
This doesnt work
acidzombie24
@acidzombie What happened when you tried it?
Yuriy Faktorovich
empty string. Guffa solved it tho. I had to seek the ms to the beginning. I ended up using his Array solution.
acidzombie24
@acidzombie Still unsure of what you mean, setting the position to 0 is the same as seeking to the beginning(as far as I read).
Yuriy Faktorovich
@Yuriy: Yes, correct. But i wasnt seeking and didnt know i should which was the problem.
acidzombie24
+1  A: 

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.

Guffa