IStream in C#: Wrap COM Streams and .NET Streams

COM APIs move binary data through the IStream interface, while .NET code works with System.IO.Stream. The two do not convert into each other automatically, so when you call a shell, imaging or Office COM API you need an adapter in one direction or the other:

  • IStreamWrapper wraps a COM IStream and exposes it as a Stream, so you can use CopyTo, StreamReader and everything else built on streams.
  • ManagedIStream wraps a .NET Stream and implements IStream, so you can hand a FileStream or MemoryStream to a COM method.

Both use System.Runtime.InteropServices.ComTypes.IStream, which is part of the base library. The code compiles on any platform, but COM itself only exists on Windows, so in practice these classes are for Windows apps. COM interop is not available when you publish with Native AOT; there you would need ComWrappers or the COM source generator instead.

Usage

using System.Runtime.InteropServices.ComTypes;

// .NET Stream -> IStream, to pass to a COM API
using FileStream file = File.OpenRead("picture.png");
IStream comStream = new ManagedIStream(file);
// someComObject.Load(comStream);

// IStream -> .NET Stream, to read what a COM API returned
using var stream = new IStreamWrapper(comStream);
using var reader = new BinaryReader(stream);
byte[] header = reader.ReadBytes(8);

Wrapping a ManagedIStream back into an IStreamWrapper is pointless in real code, but it makes a convenient test that both adapters agree.

IStream as a .NET Stream

using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using STATSTG = System.Runtime.InteropServices.ComTypes.STATSTG;

public sealed class IStreamWrapper(IStream source) : Stream
{
    private const int STATFLAG_NONAME = 1;

    // Unmanaged slot that IStream writes byte counts and positions into.
    private readonly IntPtr _scratch = Marshal.AllocHGlobal(sizeof(long));
    private bool _disposed;

    public override bool CanRead => true;
    public override bool CanSeek => true;
    public override bool CanWrite => true;

    public override long Length
    {
        get
        {
            source.Stat(out STATSTG stat, STATFLAG_NONAME);
            return stat.cbSize;
        }
    }

    public override long Position
    {
        get => Seek(0, SeekOrigin.Current);
        set => Seek(value, SeekOrigin.Begin);
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        ValidateBufferArguments(buffer, offset, count);

        // IStream.Read always fills from index 0, so use a temporary
        // buffer when the caller asks for an offset.
        byte[] target = offset == 0 ? buffer : new byte[count];
        source.Read(target, count, _scratch);
        int read = Marshal.ReadInt32(_scratch);

        if (offset != 0)
            Buffer.BlockCopy(target, 0, buffer, offset, read);

        return read;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        ValidateBufferArguments(buffer, offset, count);

        byte[] data = offset == 0 ? buffer : buffer.AsSpan(offset, count).ToArray();
        source.Write(data, count, IntPtr.Zero);
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        // STREAM_SEEK_SET/CUR/END have the same values as SeekOrigin.
        source.Seek(offset, (int)origin, _scratch);
        return Marshal.ReadInt64(_scratch);
    }

    public override void SetLength(long value) => source.SetSize(value);

    public override void Flush() => source.Commit(0); // STGC_DEFAULT

    protected override void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            Marshal.FreeHGlobal(_scratch);
            _disposed = true;
        }
        base.Dispose(disposing);
    }
}

IStream.Read, Write and Seek report their results through pointers rather than return values, and accept IntPtr.Zero when you do not care. The wrapper allocates one 8-byte unmanaged slot for those results instead of pinning a local on every call, and frees it in Dispose. That also means an instance is not thread safe, which is normal for streams.

The wrapper reports CanWrite and CanSeek as true because IStream has no way to ask. If the underlying COM stream is read-only, Write fails with a COMException carrying the COM error code.

Disposing the wrapper does not release the COM object. If you own it and want it released before the garbage collector gets to it, call Marshal.ReleaseComObject(comStream) yourself after you are done.

A .NET Stream as IStream

using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using STATSTG = System.Runtime.InteropServices.ComTypes.STATSTG;

public sealed class ManagedIStream(Stream stream) : IStream
{
    private const int STGTY_STREAM = 2;
    private const int STG_E_INVALIDFUNCTION = unchecked((int)0x80030001);

    public void Read(byte[] pv, int cb, IntPtr pcbRead)
    {
        // Stream.Read may return fewer bytes than requested before the end;
        // COM callers expect a short read to mean end of stream.
        int read = stream.ReadAtLeast(pv.AsSpan(0, cb), cb, throwOnEndOfStream: false);
        if (pcbRead != IntPtr.Zero)
            Marshal.WriteInt32(pcbRead, read);
    }

    public void Write(byte[] pv, int cb, IntPtr pcbWritten)
    {
        stream.Write(pv, 0, cb);
        if (pcbWritten != IntPtr.Zero)
            Marshal.WriteInt32(pcbWritten, cb);
    }

    public void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition)
    {
        long position = stream.Seek(dlibMove, (SeekOrigin)dwOrigin);
        if (plibNewPosition != IntPtr.Zero)
            Marshal.WriteInt64(plibNewPosition, position);
    }

    public void SetSize(long libNewSize) => stream.SetLength(libNewSize);

    public void Commit(int grfCommitFlags) => stream.Flush();

    public void Stat(out STATSTG pstatstg, int grfStatFlag)
    {
        pstatstg = new STATSTG
        {
            type = STGTY_STREAM,
            cbSize = stream.Length,
            grfMode = stream.CanWrite ? (stream.CanRead ? 2 : 1) : 0 // STGM_READWRITE / WRITE / READ
        };
    }

    public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten)
    {
        byte[] buffer = new byte[81920];
        long total = 0;

        while (total < cb)
        {
            int read = stream.Read(buffer, 0, (int)Math.Min(buffer.Length, cb - total));
            if (read == 0) break;
            pstm.Write(buffer, read, IntPtr.Zero);
            total += read;
        }

        if (pcbRead != IntPtr.Zero) Marshal.WriteInt64(pcbRead, total);
        if (pcbWritten != IntPtr.Zero) Marshal.WriteInt64(pcbWritten, total);
    }

    // Transactions, region locks and cloning have no Stream equivalent.
    public void Revert() => throw new COMException("Not supported.", STG_E_INVALIDFUNCTION);

    public void LockRegion(long libOffset, long cb, int dwLockType) =>
        throw new COMException("Not supported.", STG_E_INVALIDFUNCTION);

    public void UnlockRegion(long libOffset, long cb, int dwLockType) =>
        throw new COMException("Not supported.", STG_E_INVALIDFUNCTION);

    public void Clone(out IStream ppstm) =>
        throw new COMException("Not supported.", STG_E_INVALIDFUNCTION);
}

A few details matter here. Stat needs stream.Length, so the wrapped stream must be seekable; most COM consumers call Stat or Seek early, and a NetworkStream or GZipStream will throw NotSupportedException. Copy such streams into a MemoryStream or a temporary file first. Throwing COMException with a real STG_E_* code, rather than NotImplementedException, gives the COM caller an HRESULT it understands. ReadAtLeast requires .NET 7; on older versions, loop over Read until you have cb bytes or it returns 0.

If you are on WPF or WinForms, check whether the API you are calling already has a managed overload that accepts a Stream before writing interop code. Many do.

Related examples

Leave a Comment