Use MemoryStream to Clone a compound object
C#
1
Posts
1
Posters
0
Views
1
Watching
-
Hi, I want to clone a compound object by MemoryStream. I wrote the code in the following.
public object CloneAnObject(object objectToClone) { MemoryStream readStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(readStream, objectToClone); MemoryStream writeStream = new MemoryStream(readStream.GetBuffer()); return binaryFormatter.Deserialize(writeStream); close(readStream); close(wroteStream); }
The code usually works well, but sometimes an IOException occurs. In the help of MemoryStream.GetBuffer(), it seems the memoryStream should be closed before GetBuffer() is executed. Thank you!