My method gets MemoryStream as parameter. How can I know whether this MemoryStream is expandable?

MemoryStream can be created using an array using "new MemoryStream(byte[] buf)". This means that stream will have fixed size. You can't append data to it. On other hand, stream can be created with no parameters using "new MemoryStream()". In this case you can append data to it.

Question: How can I know - can I safely append data in a current stream or I must create a new expandable stream and copy data to it?

有帮助吗?

解决方案

You can do that using reflection:

static bool IsExpandable(MemoryStream stream)
{
    return (bool)typeof(MemoryStream)
        .GetField("_expandable", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
        .GetValue(stream);
}

I don't know if there's a cleaner/safer way to retrieve this information.

其他提示

It's not actually a fixed size in a sense, better defined as "non-expandable" since it can still be truncated via SetLength, but anyway... Probably the best thing that you can do is always use an expandable stream, or if you don't control that aspect of the code... Perhaps try catch your attempt to expand the stream and if it fails, copy it over to a writable stream and recursively call the method again?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top