Why is DataContractSerializer to StringWriter truncated?

。_饼干妹妹 提交于 2019-12-23 10:59:05

问题


I am using the DataContractSerializer to serialize EF4 objects to xml if there are exceptions. In my debug log i can see want was the data-content when something went wrong.

I have two versions of code: one version that serializes to a file and one that serializes to a string using StringWriter.

When serializing big items to file i get valid xml of about 16kb. when serializing the same item to string the xml is truncated after 12kb. Any idea what caused the truncation?

    ...
    var entity = ....
    SaveAsXml(entity, @"c:\temp\EntityContent.xml"); // ok size about 16100 btes
    var xmlString = GetAsXml(entity); // not ok, size about 12200 bytes

    // to make shure that it is not Debug.Writeline that causes the truncation
    // start writing near the end of the string
    // only 52 bytes are written although the file is 16101 bytes long
    System.Diagnostics.Debug.Writeline(xml.Substring(12200)); 

Any ideas why my string is truncated?

Here is the code to serialize to file that works ok

  public static void SaveAsXml(object objectToSave, string filenameWithPath)
  {
     string directory = Path.GetDirectoryName(filenameWithPath);
     if (!Directory.Exists(directory))
     {
        logger.Debug("Creating directory on demand " + directory);
        Directory.CreateDirectory(directory);
     }

     logger.DebugFormat("Writing xml to " + filenameWithPath);
     var ds = new DataContractSerializer(objectToSave.GetType(), null, Int16.MaxValue, true, true, null);

     var settings = new XmlWriterSettings
     {
        Indent = true,
        IndentChars = "  ",
        NamespaceHandling = NamespaceHandling.OmitDuplicates,
        NewLineOnAttributes = true,
     };
     using (XmlWriter w = XmlWriter.Create(filenameWithPath, settings))
     {
        ds.WriteObject(w, objectToSave);
     }
  }

here is the code that serializes to string that will be truncated

  public static string GetAsXml(object objectToSerialize)
  {
     var ds = new DataContractSerializer(objectToSerialize.GetType(), null, Int16.MaxValue, true, true, null);
     var settings = new XmlWriterSettings
     {
        Indent = true,
        IndentChars = "  ",
        NamespaceHandling = NamespaceHandling.OmitDuplicates,
        NewLineOnAttributes = true,
     };
     using (var stringWriter = new StringWriter())
     {
        using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
        {
           try
           {
              ds.WriteObject(xmlWriter, objectToSerialize);
              return stringWriter.ToString();
           }
           catch (Exception ex)
           {
              return "cannot serialize '" + objectToSerialize + "' to xml : " + ex.Message;
           }
        }
     }
  }

回答1:


The XmlWriter's output might not be completely flushed when you invoke ToString() on the StringWriter. Try disposing the XmlWriter object before doing that:

try
{
    using (var stringWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
        {
            ds.WriteObject(xmlWriter, objectToSerialize);
        }
        return stringWriter.ToString();
    }
}
catch (Exception ex)
{
    return "cannot serialize '" + objectToSerialize + "' to xml : " + ex.Message;
}


来源:https://stackoverflow.com/questions/5919851/why-is-datacontractserializer-to-stringwriter-truncated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!