Created
February 19, 2025 18:23
-
-
Save leviwilson/d15ac9e6557c73b2c2de0e311bfc59b2 to your computer and use it in GitHub Desktop.
MIME Detection from File Data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
namespace Northwoods.Extensions | |
{ | |
public static class MimeTypeExtensions | |
{ | |
public static string MimeType(this byte[] dataBytes, string mimeProposed = null) | |
{ | |
var mimeType = mimeProposed ?? string.Empty; | |
IntPtr outputMimeResult; | |
var status = FindMimeFromData(IntPtr.Zero, null, dataBytes, dataBytes.Length, mimeProposed, 0, out outputMimeResult, 0); | |
if (status == 0 && outputMimeResult != IntPtr.Zero) | |
{ | |
mimeType = Marshal.PtrToStringUni(outputMimeResult); | |
Marshal.FreeCoTaskMem(outputMimeResult); // msdn docs wrongly states that operator 'delete' must be used. Do not remove FreeCoTaskMem | |
} | |
return mimeType; | |
} | |
[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)] | |
internal static extern int FindMimeFromData( | |
IntPtr bindingContext, | |
[MarshalAs(UnmanagedType.LPWStr)] | |
string urlIfNotUsingByteArray, | |
[MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, SizeParamIndex=3)] | |
byte[] bytes, int bytesSize, | |
[MarshalAs(UnmanagedType.LPWStr)] | |
string defaultMimeType, | |
int mimeFlags, | |
out IntPtr foundMimeType, | |
int reserved | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment