How to properly an Outlook Object after usage? RRS feed

  • Question

  • Hi,

    i am using an outlook.application in my c# forms protoype to get the global address list.

    It works fine but after closing my app Microsoft Outlook Process is not getting closed. I can see it in the Task List. When the user closes and re-opens my application, the code throws an error. When i kill the process and open my app, everything works fine.

    How can i close the process in my app?

    This is my code:

    static void Main(string[] args)
                Outlook.Application application = GetOutlookObject();
                Outlook.AddressList gal = application.Session.GetGlobalAddressList();
                if (gal != null)
                    for (int i = 1;i < gal.AddressEntries.Count; i++)
                        Outlook.AddressEntry addrEntry = gal.AddressEntries[i];
                        Console.WriteLine(i.ToString() + " - " + addrEntry.Name);
            private static Outlook.Application GetOutlookObject()
                Outlook.Application application = null;
                // Check whether there is an Outlook process running.
                if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Count() > 0)
                    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                    application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                    // If not, create a new instance of Outlook and log on to the default profile.
                    application = new Outlook.Application();
                    Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
                    nameSpace.Logon("", "", Missing.Value, Missing.Value);
                    nameSpace = null;
                // Return the Outlook Application object.
                return application;

    Best Regards

    Developers Field Notes |

    Sunday, October 26, 2014 7:49 PM