You either need to call Flush
or cause sw
to be Close
d or Dispose
d in order to ensure that it's finished writing to the memStream
.
Also, instead of GetBuffer
, you should use ToArray
. GetBuffer
returns an internal buffer which may be larger than the amount of bytes that have actually been written.
You should also change this:
catch (Exception err)
{
// handle the error
//messageInsert = false;
}
to only catch specific exceptions for which you have a strategy to deal with them.
And, even now, I don't think it's going to do what you wanted (which you haven't really spelled out). All that your sw.Write
call does is:
Writes the text representation of an object to the text string or stream by calling the ToString method on that object.
If you want actual serialization to occur, you're going to need to write code that causes it to happen - after picking whether you want to perform binary or xml serialization.