3

I know this has been asked many times but unfortunately I haven't find a solution to my problem, I'm using urlmon.dll to find the MIME type from array of bytes but I receive a crash by the IIS process w3wp.exe

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

The code:

public static int MimeSampleSize = 256;

public static string DefaultMimeType = "application/octet-stream";

[DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private extern static uint FindMimeFromData(
    uint pBC,
    [MarshalAs(UnmanagedType.LPStr)] string pwzUrl,
    [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
    uint cbSize,
    [MarshalAs(UnmanagedType.LPStr)] string pwzMimeProposed,
    uint dwMimeFlags,
    out uint ppwzMimeOut,
    uint dwReserverd
);

public static string GetMimeFromBytes(byte[] data)
{
    try
    {
        uint mimeType;
        FindMimeFromData(0, null, data, (uint)MimeSampleSize, null, 0, out mimeType, 0);

        var mimePointer = new IntPtr(mimeType);
        var mime = Marshal.PtrToStringUni(mimePointer); // <-- Crash happens here
        Marshal.FreeCoTaskMem(mimePointer);

        return mime ?? DefaultMimeType;
    }
    catch
    {
        return DefaultMimeType;
    }
}

The crash happens right on the following line:

var mime = Marshal.PtrToStringUni(mimePointer);

I have tried to uncheck the "Suppress JIT optimization on module load" option with no luck. Also tried to change the build to x86 instead of Any CPU without any luck.

Note: I'm using 4.5 framework, IIS 8

leppie
  • 115,091
  • 17
  • 196
  • 297
SVI
  • 921
  • 4
  • 11
  • 23

1 Answers1

6

I think the problem is the signature of FindMimeFromData(). Look here at PInvoke.net for correct signature of the function:

http://www.pinvoke.net/default.aspx/urlmon/findmimefromdata.html

..so instead of uint for pBC and ppwzMimeOut you will need IntPtr!

See also:

urlmon.dll FindMimeFromData() works perfectly on 64bit desktop/console but generates errors on ASP.NET

Community
  • 1
  • 1
Kr15
  • 595
  • 1
  • 6
  • 22