Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemoryStream from HttpContent without copying

I m trying to use System.Net.Http for POST requests. I m ok with HTTP response body being in memory but need to obtain MemoryStream for it. One way to do that would be to call HttpContent.GetAsByteArrayAsync() and wrap a MemoryStream on top of it, but I think this would require content to be copied into a separate byte array (since it returns Task of byte[]).

If the response body is already in some internal buffer in HttpContent, is it possible to create MemoryStream on top of that buffer, or return MemoryStream from HttpContent somehow and avoid copying to a separate byte array?

There is also HttpContent.GetAsStreamAsync(), but that returns regular Stream, not MemoryStream. Even though it is probably an instance of MemoryStream already, I suppose it is not safe or a good practice to cast the returned stream to MemoryStream? (since this is implementation detail that could change).

Is there any other way of doing this, or do i have no choice but to copy into byte[] first?

Thanks.

like image 922
Yevgeniy P Avatar asked Nov 22 '25 14:11

Yevgeniy P


2 Answers

If you call LoadIntoBufferAsync first, ReadAsStreamAsync returns a readonly MemoryStream:

await req.Content.LoadIntoBufferAsync();
var stream = (MemoryStream) await req.Content.ReadAsStreamAsync();
like image 104
weichch Avatar answered Nov 25 '25 04:11

weichch


If you call LoadIntoBufferAsync first, CopyToAsync can be used to populate a readonly MemoryStream:

var stream = new MemoryStream(req.Content.Headers.ContentLength);
await req.Content.LoadIntoBufferAsync((int)req.Content.Headers.ContentLength);
await req.Content.CopyToAsync(stream);

This implementation doesn't depend on side effects and is supported by the docs in all framework versions: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.loadintobufferasync?view=netframework-4.6.2

Note: I tried to edit the above answer, but couldn't do it... So here you are.

like image 25
whittet Avatar answered Nov 25 '25 04:11

whittet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!