打开保存为docx然后关闭单词

时间:2014-05-23 09:42:35

标签: c# ms-word

所以我想做的是创建一个程序,选择一个带有.doc文档的地图打开,然后将其保存为docx然后关闭单词。我得到了所有,但当我尝试关闭Word时,它给了我一个错误。

主要代码:

    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();
                }
            } 
        }
    }

获取.doc文件的代码:

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);
        }
    }

它给我的错误:

  

方法'Microsoft.Office.Interop.Word._Document.Close(ref object,ref object,ref object)'和非方法'Microsoft.Office.Interop.Word.DocumentEvents2_Event.Close'之间的歧义。使用方法组。

1 个答案:

答案 0 :(得分:0)

问题是有一个方法Close()和一个事件Close。

this thread。正如海报所述,您可能希望使用Close()方法而不是事件。在这种情况下,请尝试将word.ActiveDocument转换为_Document,并在其上调用Close()。

编辑:
您还可以将类型设置为_Application,而不是Application

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

(请注意,我目前无法对此进行测试,我当前的机器上没有安装办公室)