2

I am try to write some data to the MemoryStream, and then correctly read it. For example :

int someValue = 10;
Console.WriteLine(someValue);
Console.ReadKey();
MemoryStream lMemoryStream = new MemoryStream();

StreamWriter lStreamWriter = new StreamWriter(lMemoryStream);
lStreamWriter.Write(someValue);

StreamReader lStreamReader = new StreamReader(lMemoryStream);
int someValue2 = lStreamReader.Read();
Console.WriteLine(someValue2);
Console.ReadKey();  

But in response I get empty memoryStream, and get value -1. What's wrong?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Imorian
  • 157
  • 1
  • 11
  • 1
    see about [MemoryStream.Seek](http://msdn.microsoft.com/ru-ru/library/system.io.memorystream.seek(v=vs.110).aspx) method – Grundy Feb 24 '14 at 14:46

2 Answers2

4

You forgot to flush your data into the stream. You also have to set the position to 0 if you want to read data from the beginning.

lStreamWriter.Flush(); // after .Write!
lMemoryStream.Position = 0; // before read!

Tip: Don't close the writer, it will also close the MemoryStream. Close it after you're done with the data.

Haku Douga
  • 41
  • 1
  • Or do the reading with: Encoding.SOMETHING.GetString(yourstream.GetBuffer(), 0, yourstream.Length); // reading the whole buffer and returning it as a string with the specified encoding – Haku Douga Feb 24 '14 at 14:56
  • i take wrong data...`int someValue = 10; MemoryStream lMemoryStream = new MemoryStream(); StreamWriter lStreamWriter = new StreamWriter(lMemoryStream); lStreamWriter.Write(someValue); lStreamWriter.Flush(); lMemoryStream.Position = 0; StreamReader lStreamReader = new StreamReader(lMemoryStream); int someValue2 = lStreamReader.Read(); ` i get wrong value 49 – Imorian Feb 24 '14 at 15:03
  • @Imorian Nope, that's the right value. You're writing the value as string `"10"`, and the first byte of that string is `(byte)'1' == 49`. If you want to get `"10"` back, you can do eg. `lStreamReader.ReadToEnd();` – Luaan Feb 24 '14 at 15:12
  • Exactly. The best way of getting the whole data (like I said in my first comment): byte[] buffer = lMemoryStream.ToArray(); string Data = Encoding.UTF8.GetString(buffer, 0, buffer.Length); – Haku Douga Feb 24 '14 at 15:23
  • but if a have a few filds to write? – Imorian Feb 24 '14 at 15:24
  • If you have few fields to write, work with offsets to read specific data. – Haku Douga Feb 24 '14 at 15:26
2

When you write to stream, you advance your position (in said stream). To read the value you've just written you have to "rewind" your position (by setting it).

Sergei Rogovtcev
  • 5,804
  • 2
  • 22
  • 35