Stop StreamContent class from calling Dispose on your Stream (e.g., leaveOpen: true)

Опубликовано: 01 Май 2025
на канале: David Anderson
710
17

StreamContent will dispose the underlying stream and there isn't a leave open option to avoid it. I found out that this is by design. In my scenario I need the stream to remain open after using StreamContent with HttpClient and HttpRequestMessage.

It appears the Microsoft .NET Framework team fixed this in .NET Core 2.0 and later so that System.Net.Http.StreamContent does not dispose the underlying stream anymore, but it was not backported to .NET Framework 4.8 or earlier due to some scheduling problem or complexity.

In this problem walkthrough, I explain some scenarios of why this can be a problem and why creating additional temporary streams like MemoryStream or FileStream may not be a desirable solution. I workaround the problem by implementing a DelegateStream that prevents Dispose from being called on the underlying stream.

This is using the C# (CSharp) programming language and Microsoft .NET Framework 4.8.1.

• Source Code: https://github.com/DeadX07/DX7Dev/tre...
• StreamContent Docs: https://learn.microsoft.com/en-us/dot...)
• Feature Request to add a leaveOpen parameter to the StreamContent(Stream) constructor: https://github.com/dotnet/runtime/iss...
• The fix the .NET team made: https://github.com/dotnet/corefx/pull...