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
2010-07-22 02:10:24
This doesnt work
acidzombie24
2010-07-22 04:52:13
@acidzombie What happened when you tried it?
Yuriy Faktorovich
2010-07-22 05:14:49
empty string. Guffa solved it tho. I had to seek the ms to the beginning. I ended up using his Array solution.
acidzombie24
2010-07-22 05:45:13
@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
2010-07-22 12:22:10
@Yuriy: Yes, correct. But i wasnt seeking and didnt know i should which was the problem.
acidzombie24
2010-07-22 19:53:56
+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
2010-07-22 02:24:24