Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

.net - Unable to get the correct mime type of .flv file

I want to get the mime type of local .flv file by using this function from code project http://www.codeproject.com/KB/dotnet/ContentType.aspx

Public Function GetMIMEType(_
    ByVal filepath As String) As String 
 Dim regPerm  As RegistryPermission = _
       New RegistryPermission(RegistryPermissionAccess.Read, _
       "\HKEY_CLASSES_ROOT")
 Dim classesRoot As RegistryKey = Registry.ClassesRoot
 Dim fi = New FileInfo(filepath)
 Dim dotExt As String = LCase(fi.Extension)
 Dim typeKey As RegistryKey = classesRoot.OpenSubKey(_
      "MIMEDatabaseContent Type")
 Dim keyname As String 

For Each keyname In typeKey.GetSubKeyNames()
 Dim curKey As RegistryKey = classesRoot.OpenSubKey( _
      "MIMEDatabaseContent Type" & keyname)
 If LCase(curKey.GetValue("Extension")) = dotExt Then
    'Debug.WriteLine("Content type was " & keyname)
     Return keyname
 End If
Next 
End Function  

But it returns mime type for .flv file as x-x509-ca-cert

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your approach has several disadvantages:

  • the applications must be installed to detect the mime-type
  • some mime types(f.e. htm and html) have multiple extensions, but at most one can be found in the registry
  • the extension alone says nothing about the real content of the file(you can change it manually).

Try following class to get mime types. They will be identified by a mix of sniffing the first 256 Bytes of a file(urlmon.dll - f.e. used by internet explorer) and a set of known types.

Imports System.Runtime.InteropServices
Imports System.IO

Public Class GetMimeType
    'Test-Function'
    Private Sub BtnGetMymeType_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnGetMymeType.Click
        Dim fileSelector As New System.Windows.Forms.OpenFileDialog
        If fileSelector.ShowDialog = Windows.Forms.DialogResult.OK Then
           MessageBox.Show(MimeTypes.GetContentType(fileSelector.FileName))
        End If
    End Sub
End Class

Public Class MimeTypes
    Private Shared knownTypes As List(Of String)
    Private Shared mimeTypes As Dictionary(Of String, String)

    <DllImport("urlmon.dll", CharSet:=CharSet.Auto)> _
    Private Shared Function FindMimeFromData(ByVal pBC As UInt32, <MarshalAs(UnmanagedType.LPStr)> ByVal pwzUrl As String, <MarshalAs(UnmanagedType.LPArray)> ByVal pBuffer As Byte(), ByVal cbSize As UInt32, <MarshalAs(UnmanagedType.LPStr)> ByVal pwzMimeProposed As String, ByVal dwMimeFlags As UInt32, ByRef ppwzMimeOut As UInt32, ByVal dwReserverd As UInt32) As UInt32
    End Function

    Public Shared Function GetContentType(ByVal fileName As String) As String
        If knownTypes Is Nothing OrElse mimeTypes Is Nothing Then InitializeMimeTypeLists()
        Dim contentType As String = ""
        Dim extension As String = IO.Path.GetExtension(fileName).Replace(".", "").ToLower
        mimeTypes.TryGetValue(extension, contentType)
        If String.IsNullOrEmpty(contentType) OrElse knownTypes.Contains(contentType) Then
            Dim headerType As String = ScanFileForMimeType(fileName)
            If headerType <> "application/octet-stream" OrElse String.IsNullOrEmpty(contentType) Then contentType = headerType
        End If
        Return contentType
    End Function

    Private Shared Function ScanFileForMimeType(ByVal fileName As String) As String
        Try
            Dim buffer As Byte() = New Byte(255) {}
            Using fs As New FileStream(fileName, FileMode.Open)
               Dim readLength As Integer = CInt(Math.Min(256, fs.Length))
               fs.Read(buffer, 0, readLength)
            End Using

            Dim mimeType As UInt32
            FindMimeFromData(0, Nothing, buffer, 256, Nothing, 0, mimeType, 0)
            Dim mimeTypePtr As IntPtr = New IntPtr(mimeType)
            Dim mime As String = Marshal.PtrToStringUni(mimeTypePtr)
            Marshal.FreeCoTaskMem(mimeTypePtr)
            If String.IsNullOrEmpty(mime) Then mime = "application/octet-stream"
            Return mime
        Catch ex As Exception
            Return "application/octet-stream"
        End Try
    End Function

    Private Shared Sub InitializeMimeTypeLists()
        knownTypes = New String() {"text/plain", "text/html", "text/xml", "text/richtext", "text/scriptlet", _
                                   "audio/x-aiff", "audio/basic", "audio/mid", "audio/wav", _
                                   "image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png", "image/tiff", "image/bmp", _
                                   "image/x-xbitmap", "image/x-jg", "image/x-emf", "image/x-wmf", "video/avi", "video/mpeg", _
                                   "application/octet-stream", "application/postscript", "application/base64", "application/macbinhex40", _
                                   "application/pdf", "application/xml", "application/atom+xml", "application/rss+xml", _
                                   "application/x-compressed", "application/x-zip-compressed", "application/x-gzip-compressed", _
                                   "application/java", "application/x-msdownload" _
                                   }.ToList
        mimeTypes = New Dictionary(Of String, String)
        With mimeTypes
            .Add("3dm", "x-world/x-3dmf")
            .Add("3dmf", "x-world/x-3dmf")
            .Add("a", "application/octet-stream")
            .Add("aab", "application/x-authorware-bin")
            .Add("aam", "application/x-authorware-map")
            .Add("aas", "application/x-authorware-seg")
            .Add("abc", "text/vnd.abc")
            .Add("acgi", "text/html")
            .Add("afl", "video/animaflex")
            .Add("ai", "application/postscript")
            .Add("aif", "audio/aiff")
            .Add("aifc", "audio/aiff")
            .Add("aiff", "audio/aiff")
            .Add("aim", "application/x-aim")
            .Add("aip", "text/x-audiosoft-intra")
            .Add("ani", "application/x-navi-animation")
            .Add("aos", "application/x-nokia-9000-communicator-add-on-software")
            .Add("aps", "application/mime")
            .Add("arc", "application/octet-stream")
            .Add("arj", "application/arj")
            .Add("art", "image/x-jg")
            .Add("asf", "video/x-ms-asf")
            .Add("asm", "text/x-asm")
            .Add("asp", "text/asp")
            .Add("asx", "application/x-mplayer2")
            .Add("au", "audio/basic")
            .Add("avi", "video/avi")
            .Add("avs", "video/avs-video")
            .Add("bcpio", "application/x-bcpio")
            .Add("bin", "application/octet-stream")
            .Add("bm", "image/bmp")
            .Add("bmp", "image/bmp")
            .Add("boo", "application/book")
            .Add("book", "application/book")
            .Add("boz", "application/x-bzip2")
            .Add("bsh", "application/x-bsh")
            .Add("bz", "application/x-bzip")
            .Add("bz2", "application/x-bzip2")
            .Add("c", "text/plain")
            .Add("c++", "text/plain")
            .Add("cat", "application/vnd.ms-pki.seccat")
            .Add("cc", "text/plain")
            .Add("ccad", "application/clariscad")
            .Add("cco", "application/x-cocoa")
            .Add("cdf", "application/cdf")
            .Add("cer", "application/pkix-cert")
            .Add("cha", "application/x-chat")
            .Add("chat", "application/x-chat")
            .Add("class", "application/java")
            .Add("com", "application/octet-stream")
            .Add("conf", "text/plain")
            .Add("cpio", "application/x-cpio")
            .Add("cpp", "text/x-c")
            .Add("cpt", "application/x-cpt")
            .Add("crl", "application/pkcs-crl")
            .Add("css", "text/css")
            .Add("def", "text/plain")
            .Add("der", "application/x-x509-ca-cert")
            .Add("dif", "video/x-dv")
            .Add("dir", "application/x-director")
            .Add("dl", "video/dl")
            .Add("doc", "application/msword")
            .Add("dot", "application/msword")
            .Add("dp", "application/commonground")
            .Add("drw", "application/drafting")
            .Add("dump", "application/octet-stream")
            .Add("dv", "video/x-dv")
            .Add("dvi", "application/x-dvi")
            .Add("dwf", "drawing/x-dwf (old)")
            .Add("dwg", "application/acad")
            .Add("dxf", "application/dxf")
            .Add("eps", "application/postscript")
            .Add("es", "application/x-esrehber")
            .Add("etx", "text/x-setext")
            .Add("evy", "application/envoy")
            .Add("exe", "application/octet-stream")
            .Add("f", "text/plain")
            .Add("f90", "text/x-fortran")
            .Add("fdf", "application/vnd.fdf")
            .Add("fif", "image/fif")
            .Add("fli", "video/fli")
            .Add("flv", "video/x-flv")
            .Add("for", "text/x-fortran")
            .Add("fpx", "image/vnd.fpx")
            .Add("g", "text/plain")
            .Add("g3", "image/g3fax")
            .Add("gif", "image/gif")
            .Add("gl", "video/gl")
            .Add("gsd", "audio/x-gsm")
            .Add("gtar", "application/x-gtar")
            .Add("gz", "application/x-compressed")
            .Add("h", "text/plain")
            .Add("help", "application/x-helpfile")
            .Add("hgl", "application/vnd.hp-hpgl")
            .Add("hh", "text/plain")
            .Add("hlp", "application/x-winhelp")
            .Add("htc", "text/x-component")
            .Add("htm", "text/html")
            .Add("html", "text/html")
            .Add("htmls", "text/html")
            .Add("htt", "text/webviewhtml")
            .Add("htx", "text/html")
            .Add("ice", "x-conference/x-cooltalk")
            .Add("ico", "image/x-icon")
            .Add("idc", "text/plain")
            .Add("ief", "image/ief")
            .Add("iefs", "image/ief")
            .Add("iges", "application/iges")
            .Add("igs", "application/iges")
            .Add("ima", "application/x-ima")
            .Add("imap", "application/x-httpd-imap")
            .Add("inf", "application/inf")
            .Add("ins", "application/x-internett-signup")
            .Add("ip", "application/x-ip2")
            .Add("isu", "video/x-isvideo")
            .Add("it", "audio/it")
            .Add("iv", "application/x-inventor")
            .Add("ivr", "i-world/i-vrml")
            .Add("ivy", "application/x-livescreen")
            .Add("jam", "audio/x-jam")
            .Add("jav", "text/plain")
            .Add("java", "text/plain")
            .Add("jcm", "application/x-java-commerce")
            .Add("jfif", "image/jpeg")
            .Add("jfif-tbnl", "image/jpeg")
            .Add("jpe", "image/jpeg")
            .Add("jpeg", "image/jpeg")
            .Add("jpg", "image/jpeg")
            .Add("jps", "image/x-jps")
            .Add("js", "application/x-javascript")
            .Add("jut", "image/jutvision")
            .Add("kar", "audio/midi")
            .Add("ksh", "application/x-ksh")
            .Add("la", "audio/nspaudio")
            .Add("lam", "audio/x-liveaudio")
            .Add("latex", "application/x-latex")
            .Add("lha", "application/lha")
            .Add("lhx", "application/octet-stream")
            .Add("list", "text/plain")
            .Add("lma", "audio/nspaudio")
            .Add("log", "text/plain")
            .Add("lsp", "application/x-lisp")
            .Add("lst", "text/plain")
            .Add("lsx", "text/x-la-asf")
            .Add("ltx", "application/x-latex")
            .Add("lzh", "application/octet-stream")
            .Add("lzx", "application/lzx")
            .Add("m", "text/plain")
            .Add("m1v", "video/mpeg")
            .Add("m2a", "audio/mpeg")
            .Add("m2v", "video/mpeg")
            .Add("m3u", "audio/x-mpequrl")
            .Add("man", "application/x-troff-man")
            .Add("map", "application/x-navimap")
            .Add("mar", "text/plain")
            .Add("mbd", "application/mbedlet")
            .Add("mc$", "application/x-magic-cap-package-1.0")
            .Add("mcd", "application/mcad")
            .Add("mcf", "image/vasa")
            .Add("mcp", "application/netmc")
            .Add("me", "application/x-troff-me")
            .Add("mht", "message/rfc822")
            .Add("mhtml", "message/rfc822")
            .Add("mid", "audio/midi")
            .Add("midi", "audio/midi")
            .Add("mif", "application/x-frame")
            .Add("mime", "message/rfc822")
            .Add("mjf", "audio/x-vnd.audioexplosion.mjuicemediafile")
            .Add("mjpg", "vide

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...