我最近遇到错误“ObjectDisposeException:无法访问关闭的流”
[ObjectDisposedException: Cannot access a closed Stream.]
System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +10184402
System.Security.Cryptography.CryptoStream.FlushFinalBlock() +114
System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) +48
当使用以下格式的代码时:
using (var stream = new MemoryStream())
{
using (var hashStream = new CryptoStream(stream,
new SHA256Managed(), CryptoStreamMode.Write))
using (var writer = new TextWriter(hashStream))
{
writer.Write("something");
}
// ^-- Exception occurs on hashStream Dispose
// While naively I assumed that TextWriter.Dispose wouldn't touch the
// underlying stream(s).
return stream.ToArray();
}
所以导致异常的原因是TextWriter的Dispose处理了被包装的Stream(hashStream)。我的问题是:
-
此约定(使用默认构造函数/参数)是否应用于all.NET 中的流?
是否有规范讨论这种资源使用模式?例如,是否可以假设 CryptoStream 会关闭 MemoryStream?我知道答案,就在那里还有其他专门与此相关的问题吗 https://stackoverflow.com/questions/19736631/can-a-cryptostream-leave-the-base-stream-open,但我希望根据设计指南来解决这个问题(如果有的话)。
-
此类行为记录在哪里?
我找不到其中讨论的“所有权”TextWriter(stream) http://msdn.microsoft.com/en-us/library/vstudio/wtbhzte9 or CryptoStream http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.cryptostream.aspx构造函数 - 当然我只是看错了位置。 (更新:显然我无法阅读,正如 itme86 所指出的is记录在 TextWriter 构造函数文档中。)
-
编写此类代码的普遍接受的方法是什么?
也就是说,需要读取底层流(在所有操作结束时,因此仍然打开),而所有嵌套流都应该关闭/刷新完全地- 一个简单的加密流.Flush http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.flush(v=vs.110).aspx例如,这还不够。
这一点在StreamWriter() 文档 http://msdn.microsoft.com/en-us/library/vstudio/wtbhzte9.
当调用 StreamWriter.Dispose 时,StreamWriter 对象会对提供的 Stream 对象调用 Dispose()。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)