C#VSTO Outlook错误"无法找到对象"

时间:2017-09-28 21:46:09

标签: c# visual-studio-2010 outlook vsto outlook-addin

我正在使用自定义功能区处理 Outlook AddIn 。用户在“读取”模式下打开邮件项目并单击功能区上的按钮,程序将把电子邮件移动到文件夹(不是用户的个人邮箱,而是移动到用户有权访问的其他邮箱)。

当程序运行时,它第一次运行,但是第二次用户运行它时会抛出错误:

  

"尝试的操作失败。无法找到对象。"

以下是相关代码:

(在ThisAddIn.cs中)

public partial class ThisAddIn
    {
        public Outlook.Application OutlookApplication;

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

(在Ribbon1.cs中,在按钮_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);
}

更新:试用后&错误测试,我解决Outlook 2010错误的唯一方法是让Outlook视图切换到移动邮件项目的文件夹,在命令将项目移动到myfolder后使用此命令。

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

1 个答案:

答案 0 :(得分:0)

  

当程序运行时,它第一次运行,但是第二次用户运行它时会抛出错误:

将项目移动到其他位置时,不会刷新Outlook UI。您需要自己刷新视图才能获得实时参考。任何UI对象仍保留旧引用。

例如,Move方法将Microsoft Outlook项目移动到新文件夹,返回一个Object值,该值表示已移动到指定文件夹的项目