Reusing Word instance RRS feed

  • Question

  • Hi,

    I have an application that needs to use MS Word to open a document and save it in a different format. If there is already an instance of Word open, I want to reuse this process, otherwise I want to create a new one. So every time my application needs this Word instance it calls the following code:
    private Microsoft.Office.Interop.Word.Application GetActiveApplication()
                Microsoft.Office.Interop.Word.Application app = null;
                    app = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application")
                        as Microsoft.Office.Interop.Word.Application;
                catch (Exception ex)
                    // Log exception
                if(app == null)
                       app = new Microsoft.Office.Interop.Word.Application();
                return (app);
    So if Word wasn't opened yet or if someone shut it down in the meantime, this will create a new instance; otherwise it reuses the existing.
    This works well so far, but I was wondering if there is some cleanup code I should include here - whether for the case when I create a new instance or reuse the existing one? Just remember, I do not want to close the instance either way when I'm done with using it.

    Friday, November 20, 2009 10:53 AM