1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Method To Get Mime Type Of A File Based On Extension

Discussion in 'C#' started by brandon813, Feb 13, 2013.

  1. #1
    I had to create a file binary writer that would force a file to download rather than open in a new window. I tried to identify each files MIME type based on data I found on the web. However, after searching for a while, I couldn't (and probably never will) find a complete list. So I wrote this method to get the MIME type from the Registry.
    C# Code
    /// <summary>
    /// Attempt to get the system value file type
    /// </summary>
    /// <param name="_ext"></param>
    /// <returns></returns>
    /// <remarks></remarks>
    public static string GetMimeType(string _ext)
        string mimeType = string.Empty;
        Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(_ext);
        if (regKey != null) {
            string type = (string)regKey.GetValue("Content Type");
            if (type != null) {
                mimeType = type;
        if (mimeType == string.Empty)
            mimeType = GetFileType(_ext);
        return mimeType;
    Code (markup):
    VB.Net Code
    ''' <summary>
        ''' Attempt to get the system value file type
        ''' </summary>
        ''' <param name="_ext"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GetMimeType(ByVal _ext As String) As String
            Dim mimeType As String = String.Empty
            Dim regKey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(_ext)
            If regKey IsNot Nothing Then
                Dim type As String = DirectCast(regKey.GetValue("Content Type"), String)
                If type IsNot Nothing Then
                    mimeType = type
                End If
            End If
            If mimeType = String.Empty Then mimeType = GetFileType(_ext)
            Return mimeType
        End Function
    Code (markup):
    brandon813, Feb 13, 2013 IP