none
MailItem.PropertyAccessor and Marshal.ReleaseComObject() VSTO RRS feed

  • Question

  • Hi,

    I save one MailItem with a userproperty in .msg file.

    If outlook opens the file, I read the property with PropertyAccessor:

               try
                {
                    string prop = "http://schemas.microsoft.com/mapi/string/{00020329-0000-0000-C000-000000000046}/" +
                                  propName;
                    object value = _mail.PropertyAccessor.GetProperty(prop);
                    res = value.ToString();

                }
                catch (Exception)
                {
                    //ignore
                }
                finally
                {
                    Marshal.ReleaseComObject(_mail.PropertyAccessor);
                }


    It works fine.

    But Outlook don't release the .msg file. So, if I try to open the .msg file second time, I get the message, that the file is open with another program.

    How can I get the file free?

    Thanks in advice

    Konstantin

    Friday, February 10, 2017 10:51 AM

All replies

  • Hello Konstantin,

    Do you get the same results when you save the Outlook item on the disk manually?

    First of all, you need to release all underlying COM objects instantly. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it.  Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. Read more about that in the Systematically Releasing Objects article.

    I have noticed the following lines of code:

     object value = _mail.PropertyAccessor.GetProperty(prop);

    The PropertyAccessor property of the MailItem class returns an instance of the corresponding class which should be released after.

    The following statement is not related to releasing it:

    Marshal.ReleaseComObject(_mail.PropertyAccessor);

    Instead, it gets a new instance. The reference counter is increased each time you call the property. So, you need to store in any object reference and then use it for releasing.


    profile for Eugene Astafiev at Stack Overflow, Q&A for professional and enthusiast programmers

    Friday, February 10, 2017 12:22 PM