0
votes
                    for (int i = folder.Items.Count; i > 0; i--)
                    {
                        itemsProcessedCount++;

                        if (itemsProcessedCount%100 == 0)
                        {
                            Console.WriteLine("\nNo Of Items Processed: {0}", itemsProcessedCount);
                        }

                        var a = folder.Items[i]; // Randomly getting exception here

                        if (!(a is OutLook._MailItem))
                        {
                            continue;
                        }

                        var mailItem = a as OutLook._MailItem;
                        // do the processing and move the item.
                        mailItem.Move(processedFolder);
                    }

I am trying to process mailitems from pst using Microsoft.Office.Interop.Outlook;. While processing items the application randomly throws below exception at var a = folder.Items[i];

System.Runtime.InteropServices.COMException occurred
HResult=-2147219437 Message=The operation failed. The messaging interfaces have returned an unknown error. If the problem persists, restart Outlook. Source=Microsoft Outlook ErrorCode=-2147219437
StackTrace: at Microsoft.Office.Interop.Outlook._Items.get_Item(Object Index)

I seem to get around this problem after adding sleep time.Thread.Sleep(3000); var a = folder.Items[i]; // Randomly getting exception here but again the application is crashing with the same error.

Does anybody have the solution to this? Urgently need help. Thanks.

1

1 Answers

0
votes

It's probably a race condition.

mailItem.Move(processedFolder) is probably resulting in an asynchronous update of the list of folder items, which is clashing with your code that reads the items. The Sleep probably gives the move code time to complete before you read another item.

Your best bet is to get all the items from the folder.Items variable into a list of your own BEFORE you start your move loop. Then iterate through your list, moving all the items one by one.

I'm not exactly what the interfaces exposed in your interops are, but maybe something like:

var list = folder.Items.Where(i => i is OutLook._MailItem)
                       .Cast<OutLook._MailItem>()
                       .ToList();

foreach (var item in list)
{
     // your mail-moving code here                
}