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.

4

1 回答 1

1

尝试

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);
}

我认为错过的部分是重置 MemoryStream 的位置以便能够读取(将其视为在录制后回放回放)

于 2013-07-15T03:03:28.850 回答