c# – Working with Word file in C # Unhandled exception of type "System.Runtime.InteropServices.COMException"

Question:

public static Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
        public static string generalfile = Application.StartupPath + "\\Shablon\\1.docx"; // файл-шаблон
        public static string newfile = Application.StartupPath + "\\" + Program.namePath + "\\протокол1.docx"; // новый файл на основе файла-шаблона
        public static Object fileName = generalfile;
        public static Object missing = Type.Missing;
        public void OpenFile()
        {
            app.Documents.Open(ref fileName);
        }
        public void SaveCloseFile()
        {
            app.ActiveDocument.SaveAs(newfile);
            app.ActiveDocument.Close();
            app.Quit();
        }
        public void FindReplace(string str_old, string str_new)
        {
            Microsoft.Office.Interop.Word.Find find = app.Selection.Find;

            find.Text = str_old; // текст поиска
            find.Replacement.Text = str_new; // текст замены

            find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false, MatchWildcards: false,
                        MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true, Wrap: Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue,
                        Format: false, ReplaceWith: missing, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

        }

When the file is re-created, it swears at the openFile method with a System.Runtime.InteropServices.COMException exception.

The call itself:

OpenFile();
FindReplace("name", Program.namePath);
FindReplace("Predsedatel", predsedatel_name + " - " + dolzhnostPred);
FindReplace("V1", textBox6.Text.Trim());
FindReplace("V2", textBox7.Text.Trim());
FindReplace("V3", textBox8.Text.Trim());
FindReplace("Com1", comissionname[0] + " - " + dolzhnostCom[0]);
FindReplace("Com2", comissionname[1] + " - " + dolzhnostCom[1]);
FindReplace("Com3", comissionname[2] + " - " + dolzhnostCom[2]);
FindReplace("Com4", comissionname[3] + " - " + dolzhnostCom[3]);
FindReplace("Secretar", secretar_name + " - " + dolzhnostSec);
FindReplace("ocenkaGos", Program.ocenkaGos + " %");
SaveCloseFile();

Answer:

public static Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

Once upon a time there was a Word …

app.Quit();

… but it was closed …

app.Documents.Open(ref fileName);

and then asked to open the file …
but there was no one …


In general, transfer

app = new Microsoft.Office.Interop.Word.Application();

where the work starts is somewhere before the call to OpenFile .

Scroll to Top