我正在使用自定義功能區工作於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;
這是不是表示文件夾destinationMailboxFolder不存在? –
是的,這是錯誤消息的含義,但該文件夾應該存在。這是我第一次點擊按鈕。也許當郵件被移動時,它會改變當前的上下文,答案是以某種方式將它重置回下一個項目所在的收件箱。我注意到,當我第一次單擊按鈕時,然後選擇另一個文件夾,然後回到第一個文件夾並在下一個項目上再次單擊該按鈕,它可以正常工作。 –
你確定你有合適的商店嗎? –