2012-03-20 28 views
3

我有一段允许用户发送生成文本的电子邮件的应用程序。我目前的问题是,当他们用文本加载表单时,当用户没有安装Outlook时,它会引发未处理的异常System.IO.FileNotFound。在表单的负载上,我尝试确定是否安装了Outlook。测试Outlook是否安装了C#异常处理

try{ 
     //Assembly _out = Assembly.Load("Microsoft.Office.Interop.Outlook"); 
     Assembly _out = Assembly.Load("Microsoft.Office.Interop.Outlook, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"); 
     //Microsoft.Office.Interop.Outlook.Application _out = new Microsoft.Office.Interop.Outlook.Application(); 
     //Microsoft.Office.Interop.Outlook.Application _out = new Microsoft.Office.Interop.Outlook.Application(); 
    } 

以上是我一直在尝试的代码。在我正在开发的计算机上,如果程序集名称关闭,catch语句将捕获它。但是,当我在没有outlook的XP机器上测试它时,它会抛出错误并停止加载表单事件。

每个catch语句我已经试过(捕获所有甚至不工作):

 catch (System.IO.FileLoadException) 
     { _noOutlook = true; type = "FILE-LOAD"; } 
     catch (System.IO.FileNotFoundException) 
     { _noOutlook = true; type = "FILE-NOT-FOUND"; } 
     catch (System.IO.IOException) 
     { _noOutlook = true; type = "IO"; } 
     catch (System.Runtime.InteropServices.COMException) 
     { _noOutlook = true; type = "INTEROP"; } 
     catch (System.Runtime.InteropServices.InvalidComObjectException) 
     { _noOutlook = true; type = "INTEROP-INVALIDCOM"; } 
     catch (System.Runtime.InteropServices.ExternalException) 
     { _noOutlook = true; type = "INTEROP-EXTERNAL"; } 
     catch (System.TypeLoadException) 
     { _noOutlook = true; type = "TYPELOAD"; } 
     catch (System.AccessViolationException) 
     { _noOutlook = true; type = "ACCESVIOLATION"; } 
     catch (WarningException) 
     { _noOutlook = true; type = "WARNING"; } 
     catch (ApplicationException) 
     { _noOutlook = true; type = "APPLICATION"; } 
     catch (Exception) 
     { _noOutlook = true; type = "NORMAL"; } 

我正在寻找,将工作的方法(希望,所以我可以使用一个代码为Outlook 2010年工作& 2007)而不必检查注册表/确切的文件路径。

所以我想知道的几件事是为什么XP甚至抛出错误,而不是捕捉它们,因为它会抛出FileNotFound当我有一个捕获它,以及什么是一个很好的方法来确定是否互操作对象将工作。

回答

3

我有一台2007年安装的XP机器。因此我无法测试所有情况。但是这个代码似乎工作。

public static bool IsOutlookInstalled() 
{ 
    try 
    { 
     Type type = Type.GetTypeFromCLSID(new Guid("0006F03A-0000-0000-C000-000000000046")); //Outlook.Application 
     if (type == null) return false; 
     object obj = Activator.CreateInstance(type); 
     System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); 
     return true; 
    } 
    catch (COMException) 
    { 
     return false; 
    } 
} 
+0

谢谢你,这个工作就像一个魅力。它适用于带有不带Outlook的Outlook 2010和XP的Windows 7。 – UnholyRanger 2012-03-21 13:18:36

0
public bool IsOutlookInstalled() 
{ 
    try 
    { 
     var officeType = Type.GetTypeFromProgID("Outlook.Application"); 
     if (officeType == null) 
     { 
      // Outlook is not installed. 
      return false; 
     } 
     else 
     { 
      // Outlook is installed.  
      return true; 
     } 
    } 
    catch (System.Exception ex) 
    { 
     return false; 
    } 
}