質問

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