c# - 为什么使用 StreamWriter 将文本写入字符串导致未写入任何内容?

标签 c# xml stream

我有以下代码

    public void SerializeToStream(Stream stream)
    {
        var xml = // Linq to xml code here

        // Write to the stream
        var writer = new StreamWriter(stream);
        writer.Write(xml.ToString());
    }

我的 xml对象具有正确的数据,我已验证 xml.ToString()正确显示所有内容,但在 writer.Write(xml.ToString()) 之后被称为我的传入流(无论它是 FileStream 还是 MemoryStream 仍然没有任何内容(并且长度为零)。没有抛出异常。为什么会这样?

请注意,我不能使用 xml.WriteTo()因为XmlWriter类添加了额外的东西(<xml> 声明标签),我不能在我的 xml 中添加这些东西(与我无法控制的另一个系统集成的公司政策)。

最佳答案

您永远不会刷新或关闭编写器。 (我通常建议关闭编写器,但这也会关闭流,这可能不是您想要的。)只需添加:

writer.Flush();

在方法的末尾。

请注意,如果需要,您可以从 XDocument 中删除 XML 声明。例如:

XDocument doc = new XDocument
    (new XDeclaration("1.0", "utf-8", "yes"),
     new XElement("Root", "content"));
doc.Save(Console.Out); // Includes <? xml ... ?>
doc.Declaration = null;
doc.Save(Console.Out); // No declaration...

这样应该会更简单:

public void SerializeToStream(Stream stream)
{
    var xml = // Linq to xml code here
    xml.Declaration = null;
    xml.Save(stream);
}

关于c# - 为什么使用 StreamWriter 将文本写入字符串导致未写入任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8917948/

相关文章:

android - 自定义 XML 资源中的引用字符串资源

Python 流提取

c# - 在 visual studio 2015 中停止正在进行的调试

c# - 诱发线程问题的好方法有哪些

c# - CaSTLe Windsor 重建实例

c++ - std::cin 提取到枚举

android - 从 Android 相机中提取 RGB 值

c# - 使用 WPF TabControl 的 ItemsSource 属性使其子项的 Parent 属性为 null

python - 如何使用 python lxml 获取 html 元素

java - 切换到第三个选项卡后 Tabhost 的内容被重置