6

According to .NET MemoryStream - Should I set the capacity?, it's preferred to set the initial capacity of a MemoryStream if you know it beforehand.

In my code, I'm receiving (from a third party library) a Stream object. This Stream is wrapped around a GetObjectResponse class.

Since this class will be disposed after the transaction is closed, I need to copy the received stream so I can continue using it afterwards.

The Stream class exposes a Length property to determine the length of the stream, so as an initial step to begin the copying process I started writing:

Stream destination = new MemoryStream(response.ResponseStream.Length);

But the compiler throws an error, stating that MemoryStream does not take a long parameter, instead it takes an int.

Why would they do this?

If MemoryStream extends from Stream, this means that it can have a long Length. If it can have a long size, why can't it take a long initial capactiy?

I'm trying to avoid initializing the stream with no capacity, because I want to take advantage of the fact that I know how big the stream is going to be, but the constructor seems to be constraining this wish.

How can I approach this and why does MemoryStream cannot take a long capacity?

Community
  • 1
  • 1
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154

1 Answers1

7

MemoryStream does not support more than about 2GB of data right now. This is a current limitation. It does not have to exist in principle.

This is simply a case of a feature not implemented (yet).

Implementing a bigger stream is difficult on the current CLR which only supports arrays with up to about int.MaxValue elements.

usr
  • 168,620
  • 35
  • 240
  • 369
  • 2
    It in principle has to exist. You can't index the array returned by its GetBuffer() and ToArray() members otherwise, array indices must be less than int.MaxValue. – Hans Passant Sep 15 '15 at 14:13
  • Ah, that's true. The limitation is locked into the API surface. Maybe a future CLR fixes the array length limitation, though. – usr Sep 15 '15 at 14:41