VB.NET: Get the MIME type of a file.

Posted November 29th, 2012

By running the function GetMimeType(file.name) the following code will return the MIME type for a file.

Public Shared Function GetMimeType(ByVal file As String) As String
    Dim mime As String = Nothing
    Dim MaxContent As Integer = CInt(New FileInfo(file).Length)
    If MaxContent > 4096 Then
    MaxContent = 4096
    End If

    Dim fs As New FileStream(file, FileMode.Open)

    Dim buf(MaxContent) As Byte
    fs.Read(buf, 0, MaxContent)
    Dim result As Integer = FindMimeFromData(IntPtr.Zero, file, buf, MaxContent, Nothing, 0, mime, 0)

    Return mime
End Function

<DllImport("urlmon.dll", CharSet:=CharSet.Auto)> _
Private Shared Function FindMimeFromData( _
    ByVal pBC As IntPtr, _
    <MarshalAs(UnmanagedType.LPWStr)> _
    ByVal pwzUrl As String, _
    <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.I1, SizeParamIndex:=3)> ByVal _
    pBuffer As Byte(), _
    ByVal cbSize As Integer, _
    <MarshalAs(UnmanagedType.LPWStr)> _
    ByVal pwzMimeProposed As String, _
    ByVal dwMimeFlags As Integer, _
    <MarshalAs(UnmanagedType.LPWStr)> _
    ByRef ppwzMimeOut As String, _
    ByVal dwReserved As Integer) As Integer
End Function