我如何“分叉” .NET 中的流?
void R(MemoryStream M)
{
using (B = new BinaryWriter(M))
{
// write some stuff using B
}
S(M); // now pass M to another routine for further processing
}
但是,我无法在不关闭 M
的情况下处理 BinaryStream。
问:有没有办法执行以下任一操作?
- 从 MemoryStream 中提取底层 byte[],
- 克隆 Stream
- 在关闭后重新打开 Stream
As discussed before, when a BinaryReader or BinaryWriter gets closed, its underlying Stream get closed as well (aargh). Consider this situation: a routine R
is passed a MemoryStream, say M
; I would like to write some stuff to M
and then pass it to another routine for more processing (not necessarily writing). For convenience, I'd like to wrap M
in a BinaryWriter to do my writing. After writing, I'm done with the BinaryWriter but not with M
.
void R(MemoryStream M)
{
using (B = new BinaryWriter(M))
{
// write some stuff using B
}
S(M); // now pass M to another routine for further processing
}
But, I can't dispose of the BinaryStream without closing M
.
Q: Is there a way to do any of the following?
- extract the underlying byte[] from a MemoryStream,
- clone a Stream
- reopen a Stream after it's been closed
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您最好使用 获取底层 byte[] 缓冲区
,然后使用 Array.Copy() 方法复制字节数据。
您可以自由地用它创建一个新的流。
You should better get the underlying byte[] buffer using
And then copy the byte data using the Array.Copy() method.
You are free to create a new stream with it.
您可以在 MiscUtil< 中使用诸如
MiscUtil.IO.NonClosingStreamWrapper
之类的东西/a>,它包装Stream
并简单地忽略Close
/Dispose
请求。就是为了这个目的。You can use things like the
MiscUtil.IO.NonClosingStreamWrapper
in MiscUtil, which wraps aStream
and simply ignoresClose
/Dispose
requests. For just this purpose.您可以:
You can:
感谢几个建议 ToArray 的人,我得到了正确的答案,即“M.GetBuffer”。 ToArray 还不错,但它
GetBuffer 只是获取对底层 byte[] 的引用,这就是我所追求的。
Thanks to several who suggested ToArray, I was led to right answer, which is `M.GetBuffer'. ToArray is not too bad, but it
GetBuffer just grabs a reference to the underlying byte[], which is what I'm after.
只是将其添加到此处,一个非常简单的解决方案是 不 编写器 Dispose() 。
现在您只需担心将 B 保留在范围内,即在 R() 期间。
这可能不是最好的解决方案,但值得注意的是,读者和作者不需要自行处理。
Just to add it in here, a very simple solution would be not to Dispose() the writer.
Now you only have to worry about keeping B in scope, which it will be during R().
This may not be the best solution here, but it is worth noting that the Readers and Writers don't need Disposing themselves.
一种有点幼稚的方法是使用
将流内容复制到字节数组。您可以将其转回流
A somewhat naive approach is to use
To copy the stream contents to a byte array. You can turn it back into a stream with
根据这个 M.Clone();应该有效。但我可能错了...
Accoring to this M.Clone(); should work. But i may be wrong...