1
votes

I've got a simple singleton pattern class by which my application integrates with outlook, and several of the computers that run my application do not have outlook installed. I've wrapped all the interop stuff in try-catches to avoid raising exceptions when outlook is not available, but I'm still getting automated bug reports with FileNotFound exceptions.

Here is (the relevant code) in my class:

Imports Microsoft.Office.Interop
Public Class OutlookIntegration
    Private Shared _instance As OutlookIntegration

    Public Shared Sub Initialize()
        _instance = New OutlookIntegration()
    End Sub

    Private _outlookApp As Outlook.Application
    Private _outlookNs As Outlook.NameSpace
    Private ReadOnly _outlookEnabled As Boolean

    Private Sub New()
        Try
            _outlookApp = New Outlook.Application   
            _outlookNs = _outlookApp.GetNamespace("mapi")
            _outlookNs.Logon()

        Catch ex As Exception
            _outlookApp = Nothing
            _outlookEnabled = False
            Exit Sub
        End Try

        _outlookEnabled = True
    End Sub
End Class

And the error I'm getting is this:

Message: Could not load file or assembly 'office, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified. System.IO.FileNotFoundException
at OutlookIntegration..ctor()
at OutlookIntegration.Initialize() in OutlookIntegration.vb:line 7
at MyApplication_Startup(Object sender, StartupEventArgs e) in ApplicationEvents.vb:line 139

(System.IO.FileNotFoundException) Could not load file or assembly 'office, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified.

It seems like i'm missing something simple here. Is the stack trace a red herring?

1

1 Answers

1
votes

The exception is being thrown when your private members are being loaded into memory (Outlook.Application, Outlook.NameSpace, etc.) during a call to the OutlookIntegration constructor (OutlookIntegration..ctor()) and the appropriate Outlook dependencies don't exist on the client machine.

There are several ways you could handle this:

  1. Handle the error when the constructor throws this exception (try/catch around ctor declaration in your Initialize() method)
  2. Create another class that just tests whether Outlook is installed (avoid using private members)
  3. Read the Windows registry keys which tell you whether Outlook is present or not

It's always best not to throw exceptions for performance reasons - so #3 would be my preference, but as long as you aren't continually performing this check you should be ok to use any of these options.