2

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?

Evil Beaver
  • 379
  • 3
  • 12
  • Have you tried the CanWrite property? Does it distinguish between those cases? – chris Jun 19 '13 at 15:18
  • Without more context, I'd say you shouldn't try. If the caller passes a Stream that can't accept data, they shouldn't invoke operations that would cause data to be written. That is, maybe you can improve the class's interface so that it's not an issue. – bmm6o Jun 19 '13 at 23:39
  • It always CAN accept data. You can write anything into a stream BUT available buffer is FIXED. You can't neither write outside a buffer nor extend it's capacity – Evil Beaver Jun 20 '13 at 06:12

2 Answers2

1

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.

Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
  • Nice solution :) But use Reflection for a such simple task... Think I'm just going wrong way and don't need any solutions of this question ;) I should Keep It Simple, Stupid. – Evil Beaver Jun 20 '13 at 06:23
0

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?

Haney
  • 32,775
  • 8
  • 59
  • 68