I have this code:
public static void SerializeRO(Stream stream, ReplicableObject ro) {
MemoryStream serializedObjectStream = new MemoryStream();
Formatter.Serialize(serializedObjectStream, ro);
MemoryStream writeStream = new MemoryStream();
BinaryWriter bw = new BinaryWriter(writeStream);
bw.Write(serializedObjectStream.Length);
serializedObjectStream.Seek(0, SeekOrigin.Begin);
serializedObjectStream.WriteTo(writeStream);
serializedObjectStream.Close();
writeStream.WriteTo(stream);
bw.Close();
}
The line writeStream.WriteTo(stream); never finishes. The program gets to that line and won’t progress.
stream is always a NetworkStream. I’ve checked and I think it’s a valid object (at least it’s not null nor disposed).
So what’s going on?
I tried your code – writing to a
FileStream– and I always get zero bytes written to the stream. I don’t know whyWriteTowould block on aNextWorkStreamwhen there’s nothing to write, but that could be a problemWhen I extract the bytes from the
MemoryStreamand write them directly to stream everything works e.g. (I’m creating a binary formatter in the routine, it seems you already have a formatter).However I’d do it like this with one
MemoryStreamand writing directly tostream, unless there’s something I don’t know aboutNetworkStream(this will of course closestreamwhich may not be what you want)Version that won’t close your NetworkStream (just don’t put the binary writer in a using statement or
Close()it)