user3596433
user3596433

Reputation: 5

open save as docx then close word

So what I want to do is create a program that selects a map with .doc documents open that up save it as a docx then close word. I got it all but when I try to close Word it gives me an error.

Main code:

    public void ConvertAll(string docFilePathOriginal, string docFilePath, string outputDocxFilePath)
    {
        MessageBox.Show(docFilePathOriginal);

        DocFiles = new List<string>();
        //calls the method that fills the list with the documents witht the filter.
        FindWordFilesWithDoc(docFilePathOriginal, ".doc");
        //make a new word each time for max performance
        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

        foreach (string filename in DocFiles)
        {
            //exclude the .docx files, because the filter also accepts .docx files.
            if (filename.ToLower().EndsWith(".doc"))
            {
                try
                {
                var srcFile = new FileInfo(filename);

                var document = word.Documents.Open(srcFile.FullName);
                string docxFilename = srcFile.FullName.Replace(".doc", ".docx");

                document.SaveAs2(FileName: docxFilename, FileFormat: WdSaveFormat.wdFormatXMLDocument);
                }
                finally
                {
                    word.ActiveDocument.Close();
                }
            } 
        }
    }

Code that gets the .doc files:

void FindWordFilesWithDoc(string SelectedDirection, string filter)
    {
        //get all files with the filter and add them to the list.
        foreach (string d in Directory.GetDirectories(SelectedDirection))
        {
           foreach (string f in Directory.GetFiles(SelectedDirection))
           {
               DocFiles.Add(f);
           }
            //FindWordFilesWithDoc(d, filter);
        }
    }

The error it gives me:

Ambiguity between method 'Microsoft.Office.Interop.Word._Document.Close(ref object, ref object, ref object)' and non-method 'Microsoft.Office.Interop.Word.DocumentEvents2_Event.Close'. Using method group.

Upvotes: 0

Views: 3938

Answers (1)

Deruijter
Deruijter

Reputation: 2159

The problem is that there is a method Close(), and an event Close.

See this thread. As the poster there states, you probably want to use the method Close() instead of the event. In this case try to cast word.ActiveDocument to _Document, and call Close() on that.

Edit:
You can also set the type to _Application, instead of Application:

 Microsoft.Office.Interop.Word._Application word = new Microsoft.Office.Interop.Word.Application();

(note that I'm unable to test this at the moment, I don't have office installed on my current machine)

Upvotes: 0

Related Questions