我有以下代码
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/