0

I have a VB.net code to check mime type of a file and cross check the mime file type with it's extension to validate the file. It is working fine on many machines but not working on some. I have used urlmon.dll's function FindMimeFromData.

1) ```VB.net

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, <Out()> ByRef ppwzMimeOut As IntPtr, ByVal dwReserved As Integer) As Integer
End Function
2) ```VB.net
 Public Shared Function ScanFileForMimeType(fileName As HttpPostedFile, SaveLocation As String) As String
        Dim mimeout As IntPtr
        If Not System.IO.File.Exists(SaveLocation) Then
            Throw New FileNotFoundException(SaveLocation + " not found")
        End If
        Dim MaxContent As Integer = CInt(New FileInfo(SaveLocation).Length)
        If MaxContent > 4096 Then
            MaxContent = 4096
        End If

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

        Dim buf(MaxContent) As Byte
        fs.Read(buf, 0, MaxContent)
        fs.Close()
        Dim result As Integer = FindMimeFromData(IntPtr.Zero, SaveLocation, buf, MaxContent, Nothing, 0, mimeout, 0)

        If result <> 0 Then
            'Throw Marshal.GetHRForExceptionresult)
        End If

        Dim mime As String = Marshal.PtrToStringUni(mimeout)
        Marshal.FreeCoTaskMem(mimeout)
        Return mime
    End Function

Also, will I face any problem if I use this code on Linux server? Thanks.

Wasif
  • 13
  • 3
  • What incorrect result? This needs the 'urlmon.dll' from Windows, so not usable on Linux. – David Sdot Jul 17 '19 at 05:20
  • It gives filemimetype = "application/octet-stream" for docx on some machine which is invalid. – Wasif Jul 17 '19 at 06:48
  • in that case https://stackoverflow.com/questions/4833113/why-does-the-findmimefromdata-function-from-urlmon-dll-return-mime-type-applica – David Sdot Jul 17 '19 at 08:30
  • David , I read from the link given but my question is why in some machine it is working perfectly (giving right MIME type for the uploaded document) while in some it return incorrect data. What cause the behavior change? – Wasif Jul 17 '19 at 10:03
  • Looks like the MIME gets it Data from here https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms775147%28v%3dvs.85%29 maybe different version on the pcs – David Sdot Jul 18 '19 at 05:41

0 Answers0