문제

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