C# - How to Save IntPtr Buffer Data to File (quickest way)?

Staying within the .NET framework is probably better form than using calls to kernel dlls.

I would use:

private void callback(IntPtr buffer, int length, String filename)
{
    try
    {
        FileStream file = new FileStream(filename, FileMode.Create, FileAccess.Write);
        UnmanagedMemoryStream ustream = new UnmanagedMemoryStream((byte*)buffer, length);
        ustream.CopyTo(file);
        ustream.Close();
        file.Close();
    }
    catch{/** To do: catch code **/}
}

Well, it's called "managed" for some reason :-) What you can do though is declare WriteFile using P/Invoke, like this:

private void callback(IntPtr buffer, int length)
{
    FileStream file = new FileStream(filename, FileMode.Create, FileAccess.Write);
    int written;
    WriteFile(file.Handle, buffer, length, out written, IntPtr.Zero);
    file.Close();
}

 [DllImport("kernel32.dll")]
 private static extern bool WriteFile(IntPtr hFile, IntPtr lpBuffer, int NumberOfBytesToWrite, out int lpNumberOfBytesWritten, IntPtr lpOverlapped);

Tags:

C#

Winapi