Search code examples
c#.net.net-corememorystream

Create a MemoryStream that covers a section of a byte array without copying the data in memory


I'm writing some library code, in which there is a byte[] that holds some data in memory. I would like to expose some part of the byte[] via a Stream object to the library consumer. For example, I would like the exposed Stream to be able to access the data from position 50 to the end of the byte[]. The exposed Stream would be readable and seekable, but not writable.

Is there an easy way to do this (hopefully, without writing my own Stream implementation) without creating a copy of the data in memory? I tried to use the new Memory<T> APIs, but didn't get very far because the MemoryStream constructor couldn't take a Memory<T> parameter, and it seems that I can't get a byte[] from Memory<byte> without doing a copy:

byte[] byteArray = new byte[100];
Memory<byte> memory = byteArray;

// Let's say I want to expose the second half of the byte[] via a Stream
var slicedMemory = memory.Slice(50);

// The only way to construct a MemoryStream from Memory<byte> is to call ToArray and get a byte[]
// But this makes a copy in memory, which I want to avoid
var stream = new MemoryStream(slicedMemory.ToArray(), false);

FYI I'm on .NET Core 3.1.


Solution

  • You can simply use MemoryStream - it has constructor: MemoryStream(byte[] array, int index, int count) which will create non-changeable stream over given array starting at requested index and having requested length.