0

I am trying to serialize a class to be sent to a server where the server will use that object. I am using Microsoft's example of an asynchronous client/server setup for this: http://msdn.microsoft.com/en-us/library/bew39x2a.aspx I am using the binary formatter.

To test this, I am using this class:

[Serializable]
class Class1
{
    public int x = 10;
    public string banana = "banana";

}

and attempting to serialize it with:

Class1 example = new Class1();
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, example);

in order to send it to the server, I need to send a string:

StreamReader reader = new StreamReader( stream );
string text = reader.ReadToEnd();
server.Send(text);
stream.Close();

but this doesn't work. I have tried converting the stream to a byte[] as seen here but I keep getting a Stream was unreadable exception when testing this in the debugger.

Community
  • 1
  • 1
jokul
  • 1,269
  • 16
  • 37

1 Answers1

1

Try

Class1 example = new Class1();
IFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
   formatter.Serialize(ms, example);

   ms.Position = 0;
   StreamReader sr = new StreamReader(ms);
   String text = sr.ReadToEnd();

   server.Send(text);
}

I think that the part that got missed is resetting the position of MemoryStream to be able to read (think of it as rewinding for playback after recording)

Bala R
  • 107,317
  • 23
  • 199
  • 210