tags:

views:

307

answers:

2

I'm using the Outllok Interop to move emails from one folder to another (after getting all of the attachments, but that works) but it isn't copying all of the emails. I've tried putting a wait in, but it doesn't have an effect. First it'll move 6, then 3, then 1. Can anyone tell me why its not moving them all?

Relevant code is below:

Application oOutlook = new Application();
        NameSpace oNs = oOutlook.GetNamespace("MAPI");

        Recipient oRep = oNs.CreateRecipient("ContentHelp");
        MAPIFolder inbox = oNs.GetSharedDefaultFolder(oRep, OlDefaultFolders.olFolderInbox);

        MAPIFolder nihSub = inbox.Folders["NIH"];
        MAPIFolder nihArchive = inbox.Folders["NIHarchive"];
        Items nihItems = nihSub.Items;
        MailItem moveMail = null;
        //inboxItems = inboxItems.Restrict("[Unread] = false");

        int increment = 0;

        try
        {
            foreach (object collectionItem in nihItems)
            {

                moveMail = collectionItem as MailItem;
                if (moveMail != null)
                {
                    Console.WriteLine("Moving {0}", moveMail.Subject.ToString());
                    string titleSubject = (string)moveMail.Subject;
                    moveMail.Move(nihArchive);

                }
            }
        }
+4  A: 

The index gets reset each time you loop on move , so you will never more than half the items. Use a While loop or countdown from olItems.Count to 1.

76mel
+1  A: 

A backwards loop is one that goes from the max to the min.

IE:

for(int i = 10; i>0; i--)
{
     Console.WriteLine(i);
}

For this instance you could use something like: (please note I haven't tested with the outlook objects so some tweaking may be required)

        for (int i=nihItems.count; i >= 0; i--)
        {
            moveMail collectionItem = nihItems[i] as MailItem

            if (moveMail != null)
            {
                Console.WriteLine("Moving {0}", moveMail.Subject.ToString());
                string titleSubject = (string)moveMail.Subject;
                moveMail.Move(nihArchive);
            }
         }
Nathan Koop
please note this answer was created per an anonymous user's request for the final code. This is untested against the Outlook objects, but should give a good idea of how it could be done.
Nathan Koop