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.

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.