Recently I came across a problem with Outlook PIAs. I used the Outlook library to access the Outlook Object Model. If the outlook is already running then there is no problem. But if this is not the case trying to access Application object creates a new process that's fine but when I release my objects, process is still running. At first tried tried releasing all the objects using Marshal.ReleaseComObject() but process is still there.
Code snippet is posted below
Outlook.MAPIFolder inboxFolder = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); Outlook.Items items = inboxFolder.Items;foreach (Outlook.MailItem mailItem in items) { if (mailItem.Subject == SubjectName) { //do something } Marshal.ReleaseComObject(mailItem); }Marshal.ReleaseComObject(items);Marshal.ReleaseComObject(inboxFolder);
So basically I released all the objects that i thought I was adding a reference to. But process is still there. Then I found the glitch. foreach loop is generating some intermediate reference so ref count to the com object is not decreased as it should therefor outlook process is still there even no one actually is using this.
Here is the modified code to correct the error
Outlook.MailItem item = null;Outlook.Items items = mailFolder.Items;for (item = (Outlook.MailItem)items.GetFirst(); item != null; item = (Outlook.MailItem)items.GetNext()) { if (item.Subject == SubjectName) { //do something; } Marshal.ReleaseComObject(item); } Marshal.ReleaseComObject(items);
It should work fine at least working at my Desktop :)