How to close winword.exe in my application

  • When I started my application and opened a text file, I see 3 winword.exe processes in taskmanager.
    After I called the close function 1, the winword.exe process is closed.

  • When I called worddoc.close () or wordapp.quit () in the destructor, I got the exception "A COM object that was separated from its base RCW cannot be used."

public class WordHelper
{
    private object nullobj = System.Reflection.Missing.Value;

    public string context = "";

    Microsoft.Office.Interop.Word.Document doc = new Document();
    Microsoft.Office.Interop.Word.Application wordApp = new Application();

    public WordHelper(string FileName)
    {
           //Open word file
    }

    //somefunction fo work with file

    public void CloseWord()
    {
        doc.Close();
        wordApp.Quit();
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wordApp);
    }

    ~WordHelper()
    {
        //i got exception
        doc.Close();
        wordApp.Quit();
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wordApp);
    }
}

What do I call my class

        WordHelper wddoc = new WordHelper("C:\\Test Word\\Test.docx");
        wddoc.CloseWord(); //this line i use and can close 1 process not 3
        //One process close after i close application

In the end, I want to close all winword.exe that was opened by my application, and I want to close them in the destructor. In the end, I need to close all "winword.exe" that was opened by my application, and I need to close them in the destructor.

+3
source share
2 answers

( ). , , , , , , .

Dispose pattern COM-. , .

+4

// WINWORD.exe RealTime WINWORD.exe //

Process[] proces = Process.GetProcessesByName("WINWORD");


foreach (Process proc in proces)

{

   proc.PriorityClass = ProcessPriorityClass.RealTime;
}
-2

All Articles