DataContractSerializer truncated string when used with MemoryStream,but works with StringWriter

Posted by Michael Freidgeim on Geeks with Blogs See other posts from Geeks with Blogs or by Michael Freidgeim
Published on Sat, 07 Jul 2012 10:29:12 GMT Indexed on 2012/07/10 15:17 UTC
Read the original article Hit count: 275

Filed under:
We've used the following DataContractSerializeToXml method for a long time, but recently noticed, that it doesn't return full XML for a long object, but  truncated it and returns XML string with the length of  multiple-of-1024 , but the reminder is not included.


 internal static string DataContractSerializeToXml<T>(T obj)
{
string strXml =
"";
Type type= obj.GetType();//typeof(T)
DataContractSerializer serializer = new DataContractSerializer(type);
System.IO.
MemoryStream aMemStr = new System.IO.MemoryStream();
System.Xml.
XmlTextWriter writer = new System.Xml.XmlTextWriter(aMemStr, null);
serializer.WriteObject(writer, obj);
strXml = System.Text.
Encoding.UTF8.GetString(aMemStr.ToArray());
return strXml;


  
I tried to debug and searched Google for similar problems, but didn't find explanation of the error. The most closed http://forums.codeguru.com/showthread.php?309479-MemoryStream-allocates-size-multiple-of-1024-( talking about incorrect length, but not about truncated string.

fortunately replacing MemoryStream to StringWriter according to

http://billrob.com/archive/2010/02/09/datacontractserializer-converting-objects-to-xml-string.aspx
fixed the issue.

  1: var serializer = new DataContractSerializer(tempData.GetType());
  2: using (var backing = new System.IO.StringWriter())
  3: using (var writer = new System.Xml.XmlTextWriter(backing))
  4: {
  5:     serializer.WriteObject(writer, tempData);
  6:     data.XmlData = backing.ToString();
  7: }
v

© Geeks with Blogs or respective owner