Friday, December 2, 2011

Getting Installed Version of Microsoft Office in .NET

Getting Installed Version of Microsoft Office in .NET

Private Function iCheck_Excel_Version_Installed(ByVal pMsgTitle As String) As Integer

        'The subkey's string value we check is like
        'Excel.Application.<version>, i e Excel.Application.10

        'The subkey we are interested of is located under the
        'HKEY_CLASSES_ROOT class.
        Const stXL_SUBKEY As String = "\Excel.Application\CurVer"

        Dim rkVersionKey As RegistryKey = Nothing
        Dim stVersion As String = String.Empty
        Dim stXLVersion As String = String.Empty

        'A very simple regular expression where:
        '[8-9] means look for the numbers 8 and 9
        'and start in the end of the expression.
        'Dim stRegExpr As String = "[8-9]$"

        'If we need to make sure that for instance Excel 2003 (11) or
        'later is installed then the above expression can be modified
        'to:
        'Dim stRegExpr As String = "[8-9]$|[1]0$"
        Dim stRegExpr As String = "[8-9]$|[1][0-1]$"

        Dim iVersion As Integer = Nothing

        Try
            'Here we try to open the subkey.
            rkVersionKey = Registry.ClassesRoot.OpenSubKey(name:=stXL_SUBKEY, _
                                                           writable:=False)

            'If it does not exist it means that Excel is not installed at all.
            If rkVersionKey Is Nothing Then
                iVersion = 0
                Return iVersion
            End If

            'OK, Excel is installed let's find out which version is available.
            stXLVersion = CStr(rkVersionKey.GetValue(name:=stVersion))

            'Here we match the retrieved value with our created regular
            'expression.
            If Regex.IsMatch(input:=stXLVersion, pattern:=stRegExpr) Then
                'Either Excel 97 or Excel 2000 is installed.
                iVersion = 1
                Return iVersion
            Else
                'Excel 2002 or later is available.
                iVersion = 2
                Return iVersion
            End If
        Catch ex As Exception
            System.Windows.Forms.MessageBox.Show(ex.Message, pMsgTitle,   
             Windows.Forms.MessageBoxButtons.OK, Windows.Forms.MessageBoxIcon.Error)
            Return Nothing
        Finally
            If Not rkVersionKey Is Nothing Then rkVersionKey.Close()
        End Try
    End Function

No comments:

Post a Comment