<PackageReference Include="System.Drawing.Common" Version="10.0.0-preview.2.25163.9" />

StreamExtensions

static class StreamExtensions
using System.Runtime.CompilerServices; using Windows.Win32; using Windows.Win32.Foundation; using Windows.Win32.System.Com; using Windows.Win32.System.Memory; namespace System.IO { internal static class StreamExtensions { internal static ComScope<IStream> ToIStream([Nullable(1)] this Stream stream, bool makeSeekable = false) { ArgumentNullException.ThrowIfNull(stream, "stream"); return ComHelpers.GetComScope<IStream>(new ComManagedStream(stream, makeSeekable)); } [NullableContext(1)] internal unsafe static HRESULT SaveStreamToHGLOBAL(this Stream stream, ref HGLOBAL hglobal) { if (!hglobal.IsNull && !PInvokeCore.GlobalFree(hglobal).IsNull) return HRESULT.E_OUTOFMEMORY; int num = checked((int)stream.Length); hglobal = PInvokeCore.GlobalAlloc(GLOBAL_ALLOC_FLAGS.GMEM_MOVEABLE, (UIntPtr)(uint)num); if (hglobal.IsNull) return HRESULT.E_OUTOFMEMORY; void* ptr = PInvokeCore.GlobalLock(hglobal); if (ptr == null) return HRESULT.E_OUTOFMEMORY; try { Span<byte> buffer = new Span<byte>(ptr, num); stream.Position = 0; stream.ReadExactly(buffer); } finally { PInvokeCore.GlobalUnlock(hglobal); } return HRESULT.S_OK; } } }