2017-09-28 68 views
0

我正在使用自定义功能区工作于Outlook AddIn。用户在阅读模式下打开邮件项目并单击功能区上的按钮,程序将电子邮件移动到文件夹(不是用户的个人邮箱,而是到用户有权访问的其他邮箱)。C#VSTO Outlook错误“无法找到对象”

当程序运行时,它的工作原理是第一次,但用户运行它的第二次,它抛出一个错误:

"The attempted operation failed. An object could not be found."

下面是相关代码:

(中的ThisAddIn的.cs)

public partial class ThisAddIn 
    { 
     public Outlook.Application OutlookApplication; 

     void ThisAddIn_Startup(object sender, System.EventArgs e) 
     { 
      OutlookApplication = this.Application; 
     } 
(etc) 

(在Ribbon1.cs,在该能够顺利通过button_Click调用)方法

Outlook.Inspector inspector = Globals.ThisAddIn.OutlookApplication.ActiveInspector(); 
Outlook.MailItem item = inspector.CurrentItem as Outlook.MailItem; 
Outlook.Stores stores = null; 
Outlook.Folder destinationMailboxFolderInbox = null; 

try 
{ 
    // Set the mailbox move location 
    stores = Globals.ThisAddIn.OutlookApplication.GetNamespace("MAPI").Stores; 

    foreach (Outlook.Store store in stores) 
    { 
     attachmentsFoundTotal++; 
     if (store.DisplayName == destinationMailbox) 
     { 
      destinationMailboxFolderInbox = (Outlook.Folder)store.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); 
      try 
      { 
       // the code breaks on this line below: 
       item.Move(destinationMailboxFolderInbox.Folders[destinationMailboxFolder]); 
      } 
      catch (Exception ex3) 
      { 
       System.Windows.Forms.MessageBox.Show(ex3.Message + " Could not find Outlook folder " + destinationMailboxFolder + ". The mail item was not moved." ); 
      } 
     } 
    } 
} 
catch (Exception ex2) 
{ 
    System.Windows.Forms.MessageBox.Show(ex2.Message); 
} 

UPDATE:试验&错误的测试后,我可以解决Outlook 2010中错误的唯一方法是让Outlook视图切换到邮件项目被移动的文件夹,使用此命令在将项目移动到我的文件夹之后执行。

Globals.ThisAddIn.OutlookApplication.ActiveExplorer().CurrentFolder = myFolder; 
+0

这是不是表示文件夹destinationMailboxFolder不存在? –

+0

是的,这是错误消息的含义,但该文件夹应该存在。这是我第一次点击按钮。也许当邮件被移动时,它会改变当前的上下文,答案是以某种方式将它重置回下一个项目所在的收件箱。我注意到,当我第一次单击按钮时,然后选择另一个文件夹,然后回到第一个文件夹并在下一个项目上再次单击该按钮,它可以正常工作。 –

+0

你确定你有合适的商店吗? –

回答

0

When the program is run, it works the first time, but the second time the user runs it, it throws an error:

在Outlook用户界面,当一个项目被移动到另一个地方不会刷新。您需要自行刷新视图以获取实时参考。任何UI对象仍然保留旧的引用。

例如,Move方法移动一个Microsoft Outlook项目到新文件夹和返回表示已经移动到指定的文件夹的项的对象的值。

相关问题