为什么使用StreamWriter将文本写入字符串而导致没有写入?

Kal*_*exx 1 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());
    }
Run Code Online (Sandbox Code Playgroud)

我的xml对象有正确的数据,我已经验证xml.ToString()正确显示的一切,但毕竟writer.Write(xml.ToString())叫我输入流(如果不管它是一个FileStreamMemoryStream仍具有它没有(和一个长度为零).没有异常抛出,这是为什么发生了什么?

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

Jon*_*eet 7

你永远不会冲洗或关闭作家.(我通常建议关闭作者,但这也会关闭流,这可能不是你想要的.)只需添加:

writer.Flush();
Run Code Online (Sandbox Code Playgroud)

在方法的最后.

请注意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...
Run Code Online (Sandbox Code Playgroud)

这应该更简单:

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