为什么DataContractSerializer被截断的StringWriter?

时间:2011-05-07 08:04:39

标签: c# .net serialization datacontractserializer stringwriter

如果有异常,我正在使用DataContractSerializer将EF4对象序列化为xml。 在我的调试日志中,我可以看到当出现问题时想要的是数据内容。

我有两个版本的代码:一个版本序列化为文件,另一个版本使用StringWriter序列化为字符串。

将大项目序列化到文件时,我得到的有效xml约为16kb。 当序列化相同的项目到字符串时,xml在12kb之后被截断。知道导致截断的原因吗?

    ...
    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)); 

我的字符串被截断的任何想法?

以下是序列化为文件的代码正常

  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);
     }
  }

这是序列化为将被截断的字符串的代码

  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 个答案:

答案 0 :(得分:8)

XmlWriter上调用ToString()时,StringWriter的输出可能无法完全刷新。在执行此操作之前,请尝试处理XmlWriter对象:

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;
}