Friday, January 27, 2006

Having problems while deleting Office objects?

Do you encounter problems while deleting objects in Office applications with VSTO 2005 - Visual Studio Tools for Office 2005? This is because of the underlying Office Object model and although you seem to be doing the right thing with iterating through the objects in a collection and deleting them - and the compiler does not raise any errors - most of the time at runtime your code results with unexpected behavior. (it deletes the wrong object, does not delete all objects etc.)

Here is a code with problem:

foreach (Outlook.Attachment _attachment in _mailItem.Attachments)
{ _attachment.Remove }


So here is what you should do: instead of deleting during iteration, create a new .NET Collection, add the objects (in our example attachments) to that collection within the foreach clause and after that delete the objects in the .NET collection.

Happy coding!

No comments: