简体   繁体   English

StreamReader和StreamWriter在同一个Stream上?

[英]StreamReader and StreamWriter on the same Stream?

How do I manage closing StreamReader and StreamWriter which are using the same underlying stream? 如何管理使用相同底层流的关闭StreamReaderStreamWriter

var stream = /*...*/;
var reader = new StreamReader(stream);
var writer = new StreamWRiter(stream);

I know that I could simply ignore closing the reader/writer and just close the underlying stream. 我知道我可以简单地忽略关闭读取器/写入器并关闭底层流。 However, that seems a bit of a hack, since it is based on the assumption that the reader/writer doesn't have anything to dispose (which might not be the case in the future). 然而,这看起来有点像黑客,因为它基于读者/作者没有任何东西要处理的假设 (未来可能不会这样)。

I know this have been solved in .NET 4.5 with an extra constructor argument, but until .NET 4.5 is released, how do I solve it in a proper way? 我知道这已经在.NET 4.5中使用额外的构造函数参数解决了,但是在.NET 4.5发布之前,我该如何以正确的方式解决它?

Make sure you Flush() the writer first. 确保先Flush()

And then just Dispose or Close the 2 decorators and the stream (nested usings are OK). 然后只需处理或关闭2个装饰器和流(嵌套使用即可)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM