Reputation: 13133
I need to convert a byte[] array into a stream (e.g. for uploading a file), then in another part of my code, convert a stream back into an array (e.g. for downloading a file). Is there a way to do these operations without making a copy of the byte arrays?
This bit of code shows that MemoryStream creates copies. I want to trade the safety for better memory performance.
static void Main(string[] args)
{
byte[] array1 = new byte[1024];
using (MemoryStream s = new MemoryStream(array1))
{
byte[] array2 = s.ToArray();
Console.WriteLine(Object.ReferenceEquals(array1, array2)); // "false"
}
}
Upvotes: 1
Views: 182
Reputation: 1503429
You can use MemoryStream.GetBuffer
to avoid copying. Just bear in mind that that's the "raw" backing buffer, which may be longer than the stream's notional length.
Alternatively, if you're providing the byte array to start with, you can just use that afterwards too:
byte[] buffer = new byte[1024];
using (MemoryStream stream = new MemoryStream(buffer))
{
// Write to it here
}
// Now buffer will contain the written data
Again, you need to work out exactly how much data has actually been written.
Upvotes: 5