Question : ASP.NET - object serialization

I'm trying to serialize an object and store it as a string into a hidden textbox on a web form.  I posted below the code I've tried so far to make this happen.

The history object is a Stack<String> and I have verified that it does in fact have data, but the reader.ReadToEnd() method returns back an empty string.

Can someone correct me and show me what I may be doing wrong with this code?

Thanks.
1:
2:
3:
4:
5:
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, history);
StreamReader reader = new StreamReader(stream);
txtHistorySerialized.Text = reader.ReadToEnd();

Answer : ASP.NET - object serialization

Fairly simple fix. When you write to the memory stream the stream pointer is still pointing at the last write position (i.e. the end of the stream) so when you do a ReadToEnd() you are basically already at the end of the stream, hence you get nothing back.

All you need to do is to move the pointer back to the start of the stream before attempting to read:

1:
2:
3:
4:
5:
6:
7:
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, history);    // writes to the stream but leaves the pointer at the end of the stream

stream.Position = 0;   // move the pointer back to the start of the stream before attempting to read
StreamReader reader = new StreamReader(stream);
txtHistorySerialized.Text = reader.ReadToEnd();
Random Solutions  
 
programming4us programming4us