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

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);
MemoryStream aMemStr = new System.IO.MemoryStream();
XmlTextWriter writer = new System.Xml.XmlTextWriter(aMemStr, null);
serializer.WriteObject(writer, obj);
strXml = System.Text.
return strXml;

I tried to debug and searched Google for similar problems, but didn’t find explanation of the error. The most closed talking about incorrect length, but not about truncated string.

fortunately replacing MemoryStream to StringWriter according to
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: }