My add-in is using Visual Studio 2010 targeting Outlook 2007. One task of the add-in is to move all the mailitems from a folder to a designated folder.
My first phase of testing simply modified the subject and saved the email in the same folder. No problems there.
When I changed from the .Save method to use the .Move method, I cannot process all of the items. Some get moved then the foreach loop exits prematurely without throwing any exception.
My test data appears to me to quite controlled in that I move items manually into the folder I want to process before I step thru the code with the debugger. For example, with 4 mailitems in the folder, I can move 2 of them and when the foreach is revisited it goes to exit the loop leaving 2 mailitems unprocessed.
Any ideas?
if (ProcessFolder(theRootFolder.FolderPath) && (theRootFolder.Items.Count > 0))
{
int itemCount = theRootFolder.Items.Count;
int loopCount = 0;
MetaDataForm getMetaData = new MetaDataForm(theRootFolder.FolderPath, theRootFolder.Items.Count);
getMetaData.ShowDialog();
if (getMetaData.DialogResult == DialogResult.OK)
{
string d1 = getMetaData.Meta1;
string d2 = getMetaData.Meta2;
try
{
foreach (Object item in theRootFolder.Items)
{
loopCount++;
Outlook.MailItem mi = item as Outlook.MailItem;
if (mi != null)
{
mi.Move(_TRIM_archiveFolder);
}
}
}
catch (Exception ex)
{
ex.ToString();
MessageBox.Show(String.Format("ItemCount={0},LoopCount={1},ExceptionData={2}",
itemCount, loopCount, ex));
}
MessageBox.Show(String.Format("ItemCount={0},LoopCount={1}",
itemCount, loopCount));
}
}
EDIT:
Great idea….looping backwards solved the problem:
// iterating backwards is needs because of .move below
for (int i = theRootFolder.Items.Count; i > 0; i--)
{
Outlook.MailItem mi = (Outlook.MailItem)theRootFolder.Items[i];
if (mi != null)
{
if (!mi.Subject.StartsWith("M1"))
{
mi.Move(_TRIM_archiveFolder);
}
}
}
Generally when using
foreach, the runtime does not like it too much when the collection being iterated changes.I’m taking a wild guess here, but I think the reason why you can move 2 out of your 4 items is that when you come to your third iteration the two items that are left has moved in the
Itemscollection and are now on position 0 and 1, while you are looking at position 2.Use a for loop or a while loop with Items.Count() > 0 or something like that.
I’m also guessing that you in fact are getting an exception when this happens, but it never pops up to you. Try to attach the process in WinDbg and see what’s going on. You are probably getting a COM Error of some kind.
Aren’t the Outlook APIs pretty much still all COM libraries?
EDIT:
Your idea was right. Gave me the idea to iterate backwards: