如何检查 C# Stream 的大小是否可调整?
来自 http://msdn。 microsoft.com/en-us/library/system.io.memorystream%28v=VS.90%29.aspx:
使用无符号字节数组创建的内存流提供了 不可调整大小的数据流。当使用字节数组时,您可以 既不追加也不缩小流,尽管您可能可以 根据传入的参数修改现有内容 构造函数。空内存流的大小是可以调整的,并且可以 写入和读取。
当提供对 MemoryStream
(甚至只是一个 Stream
)的引用时,如何检查它是否可调整大小?
使用 OpenXML SDK 时会出现这种情况,它要求传递给它的流可以调整大小。我可以通过深度复制到可调整大小的流来确保可调整大小,我只是想知道是否有特殊原因导致库在向其传递错误参数(即不可调整大小的流)时不抛出异常。
From http://msdn.microsoft.com/en-us/library/system.io.memorystream%28v=VS.90%29.aspx:
Memory streams created with an unsigned byte array provide a
non-resizable stream of the data. When using a byte array, you can
neither append to nor shrink the stream, although you might be able to
modify the existing contents depending on the parameters passed into
the constructor. Empty memory streams are resizable, and can be
written to and read from.
When provided a reference to a MemoryStream
(or even just a Stream
), how can one check if it's resizable?
The situation arose when using the OpenXML SDK, which requires the streams passed to it be resizable. I can ensure resizability by deep copying to a resizable stream, I'm just wondering if there's a particular reason why the library doesn't throw an exception when a bad parameter is passed to it (i.e. an unresizable stream).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种在尝试调整大小时捕获 NotSupportedException 的丑陋方法。
Here's one kinda ugly way were you catch the NotSupportedException when attempting to resize.
编辑:以下解决方案不适用于使用带有最后一个参数的
MemoryStream(byte[], int, int, bool, bool)
构造函数创建的 MemoryStreams < code>publiclyVisible 设置为true
。根据 MSDN,
MemoryStream。如果对象不是使用“公开可见的缓冲区”创建的,GetBuffer
将抛出UnauthorizedAccessException
。列出的具有公开可见缓冲区的构造函数可以方便地映射到可调整大小的相同构造函数。因此,您可以通过检查GetBuffer
来检查它的大小是否可调整:Edit: the below solution doesn't work for MemoryStreams that were created using the
MemoryStream(byte[], int, int, bool, bool)
constructor with the last parameterpubliclyVisible
set totrue
.According to MSDN,
MemoryStream.GetBuffer
will throw anUnauthorizedAccessException
if the object was not created with a "publicly visible buffer". The constructors listed with publicly visible buffers conveniently map to the sames ones that are resizable. So you could check that it's re sizable by checkingGetBuffer
: