为什么使用 StreamWriter 将文本写入字符串会导致没有写入任何内容?
我有以下代码
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 中包含(与我无法控制的另一个系统集成的公司政策)。
I have the following code
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());
}
My xml
object has the correct data, and I have verified that xml.ToString()
shows everything correctly, but after writer.Write(xml.ToString())
is called my incoming stream (regardless if it's a FileStream
or MemoryStream
still has nothing in it (and a length of zero). No exceptions are thrown. Why is this happening?
As a note, I cannot use xml.WriteTo()
because the XmlWriter
class adds extra stuff (the <xml>
declaration tag) which I cannot have in my xml (Company policy for integration with another system I do not have control over).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你永远不会刷新或关闭 writer。 (我通常建议关闭编写器,但这也会关闭流,这可能不是您想要的。)只需
在方法末尾添加:即可。
请注意,如果需要,您可以从
XDocument
中删除 XML 声明。例如:这应该会让事情变得更简单:
You're never flushing or closing the writer. (I'd normally suggest closing the writer, but that will also close the stream, which may not be what you want.) Simply add:
at the end of the method.
Note that you can remove the XML declaration from an
XDocument
, if you want. For example:That should make it simpler:
我敢打赌这是因为你没有关闭 StreamWriter;冲洗可能也会起作用。
将其包装在 using 块中将为您解决这两个问题。
注意(来自@Tigran):
using
:这也会影响流对象,这在接受像参数这样的流的函数中可能不是一个好的选择。I would bet it's because you're not closing the StreamWriter; flushing would likely work as well.
Wrapping it in a using block will take care of both for you.
Note (from @Tigran):
using
: this will affect also the stream object, which may be not a good choice in the function which accepts a stream like a parameter.作为一般规则,任何时候您使用实现 IDisposable 接口的类时,都应该将其包含在 using 块中。这可确保在对象超出范围之前调用 .Close() 方法,从而释放资源。我还注意到,如果末尾没有 .Flush() ,内容并不总是会被写出。
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
As a general rule, any time you are using a class that implements the IDisposable interface, you should really enclose it in a using block. This ensures that the .Close() method is called before the object goes out of scope, freeing up resources. I've also noticed that without a .Flush() at the end, the contents don't always get written out.
http://msdn.microsoft.com/en-us/library/yh598w02.aspx