Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .Net4: Properly disposing (dynamic) COM objects

I need to automate office documents (Word & Excel) from my .Net4 app.

Since I can't really force my users to use a specific Office version I don't use interop assemblies or tlbimp, so my project doesn't contain any additional references nor will the whole app fail if Office is not installed (feature just won't be available).

Instead I ask the system which COM server can handle "Word.Application" or "Excel.Application":

dynamic app = Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"));
app.Foo();

I'm concerned how to properly dispose of the "app" object when I'm done with it, since now I have two internal management systems to worry about (COM reference counting and .Net reference tracking). Ideally I should be able to wrap the dynamic app object into a disposable wrapper class and to be sure that underlying COM object is unreferenced when the wrapper is disposed of.

EDIT: Also I'd like to know how to properly make the COM object "live on" when I'm done with it, since Word is in a separate process. I should be able to instantiate Word app, automate it and then free all my references but the Word app should stay open.

like image 243
Boris B. Avatar asked Feb 28 '11 10:02

Boris B.


1 Answers

I would definitely implement IDisposable and call Marshal.ReleaseComObject within it. Make sure you correctly implement the disposable pattern to avoid releasing the COM object more than once and reducing the reference count further than you should, although this may not matter if you are only going to create one instance of the COM object. I have implemented this pattern successfully in the past so you are definitely heading in the right direction.

I think Word will remain open even when the last COM object is reference counted to 0 in your app, unless you explicitly ask it to exit. ( Word.Application.Close() ?)

like image 76
James Webster Avatar answered Sep 30 '22 02:09

James Webster