为什么 DataContractSerializer 到 StringWriter 会被截断?

发布于 2024-11-05 18:41:36 字数 2511 浏览 3 评论 0原文

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

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

当将大项目序列化到文件时,我得到大约 16kb 的有效 xml。 当将同一项目序列化为字符串时,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;
           }
        }
     }
  }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城泪 2024-11-12 18:41:36

当您在 StringWriter 上调用 ToString() 时,XmlWriter 的输出可能不会完全刷新。在执行此操作之前尝试处置 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;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文