Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing of Microsoft.Office.Interop.Word.Application

(Somewhat of a follow on from the post (which remains unanswered): https://stackoverflow.com/q/6197829/314661)

Using the following code

Application app = new Application(); _Document doc = app.Documents.Open("myDocPath.docx", false, false, false); doc.PrintOut(false); doc.Close(); 

I am attempting to open and print a file programmatically.

The problem is each time I run the above code a new WINWORD.exe process is started and obviously this quickly eats up all the memory.

The application class doesn't seem to contain a dispose/close or similar method.

After a bit of research I (realized) and changed the code to the following.

 Application app = new Application();  _Document doc = app.Documents.Open(fullFilePath + ".doc", false, false, false);  doc.PrintOut(false);  doc.Close();  int res = System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);  int res1 = System.Runtime.InteropServices.Marshal.ReleaseComObject(app); 

And I can see the remaining reference count is zero but the processes remain?

PS: I'm using Version 14 of the Microsoft.Office.Interop library.

like image 448
Maxim Gershkovich Avatar asked Jul 21 '11 14:07

Maxim Gershkovich


People also ask

Does Microsoft Office Interop Word require Word to be installed?

You cannot use the Interop libraries without Office installed. This is a requirement from Microsoft, so even if you figured out how to do it you would be violating the EULA. There are alternatives (Aspose, OOXML SDK, etc.) that might be useful but to use Interop on the server, you need to install Office.

How do you close Microsoft Word application?

Step 1: Press the 'CTRL + F4' keys simultaneously to close the Word File.


2 Answers

Do you not need to call Quit?

app.Quit(); 
like image 121
Enigmativity Avatar answered Sep 28 '22 19:09

Enigmativity


Perhaps try setting doc = null and calling GC.Collect()

Edit, not really my own code I forget where I got it but this is what I use to dispose of Excel, and it does the job maybe you can glean something from this:

public void DisposeExcelInstance() {     app.DisplayAlerts = false;     workBook.Close(null, null, null);     app.Workbooks.Close();     app.Quit();     if (workSheet != null)         System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);     if (workBook != null)         System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);     if (app != null)         System.Runtime.InteropServices.Marshal.ReleaseComObject(app);     workSheet = null;     workBook = null;     app = null;     GC.Collect(); // force final cleanup! } 
like image 30
Nick Avatar answered Sep 28 '22 19:09

Nick