Home Articles VB.Net Articles Get the associated application for a file extension

Get the associated application for a file extension

Sometimes its necessary for us to identify what application is associated with a particular file extension, the following snippet of code will read the Windows registry to identify what application a particular file extension is opened with by default.

    ''' <summary>
    ''' This method deals with getting the path of the application that is specified to open
    ''' a particular extension
    ''' </summary>
    ''' <param name="ext">The extension to get the associated application for</param>
    ''' <returns>The path of the application that is associated to the specified extension</returns>
    ''' <remarks>Returns a zero length string if the extension is not found</remarks>

    Public Shared Function getApplicationForExtension(ByVal ext As String) As String
        Dim key As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot
        Dim secondKey As String
        Dim rtn As String = ""

        If Not ext.StartsWith(".") Then
            ext = "." & ext
        End If

        key = key.OpenSubKey(ext)

        If key IsNot Nothing Then
            secondKey = key.GetValue("").ToString()

            If secondKey <> "" Then
                key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(secondKey & "\Shell\Open\Command")
                rtn = key.GetValue("").ToString()
                rtn = System.Text.RegularExpressions.Regex.Match(rtn, "\""(.*?)\""").Groups(0).Value
            End If
        End If

        Return rtn
    End Function