# OleSaveToStream

\[System.Runtime.InteropServices.DllImport("OLE32.DLL", EntryPoint = "CreateStreamOnHGlobal")]     // Create a COM stream from a pointer in unmanaged memory     extern public static int CreateStreamOnHGlobal(IntPtr ptr, bool delete, out System.Runtime.InteropServices.ComTypes.IStream pOutStm);

&#x20;   \[DllImport("OLE32.DLL", ExactSpelling = true, PreserveSig = false)]     private static extern void OleSaveToStream(IPersistStreamInit pPStm, IStream pStm);

&#x20;      public int ByteSizeOfIPStreamInit(IPersistStreamInit pPersistStream)        {          int     iSzOfStreamInBytes=0;          IntPtr  ptrIStream = IntPtr.Zero;          IStream IPtrStream;

&#x20;        if (CreateStreamOnHGlobal(ptrIStream, true, out IPtrStream) == 0)          {               OleSaveToStream(pPersistStream,IPtrStream);               iSzOfStreamInBytes = IStreamSizeRead(IPtrStream);          }          return (iSzOfStreamInBytes \* 2); // (Multiply By 2 because Int32 is 4 bytes; Use caution.)        }

&#x20;   public int IStreamSizeRead(IStream pOutStm)     {         pOutStm.Seek(0, 0, IntPtr.Zero);// Get size of the stream and read its contents to a byte array.         System.Runtime.InteropServices.ComTypes.STATSTG fileinfo;         pOutStm.Stat(out fileinfo, 0);         byte\[] data = new byte\[fileinfo.cbSize];         int sizeOfInt32 = Marshal.SizeOf(typeof(int));         IntPtr pRead = Marshal.AllocHGlobal(sizeOfInt32);         pOutStm.Read(data, data.Length, pRead);         int read = Marshal.ReadInt32(pRead);         Marshal.FreeHGlobal(pRead);         return (data.Length);     }


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pinvokeisalive.gitbook.io/pinvoke/desktopfunctions/ole32/olesavetostream.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
