C# 打开另存为docx,然后关闭word
所以我要做的是创建一个程序,用.doc文档选择一个地图,打开它,将其保存为docx,然后关闭word。我完全明白了,但当我试图关闭Word时,它会给我一个错误 主要代码:C# 打开另存为docx,然后关闭word,c#,ms-word,C#,Ms Word,所以我要做的是创建一个程序,用.doc文档选择一个地图,打开它,将其保存为docx,然后关闭word。我完全明白了,但当我试图关闭Word时,它会给我一个错误 主要代码: public void ConvertAll(string docFilePathOriginal, string docFilePath, string outputDocxFilePath) { MessageBox.Show(docFilePathOriginal); D
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();
}
}
}
}
它给我的错误是:
方法“Microsoft.Office.Interop.Word.\u Document.Close(ref-object,ref-object,ref-object)”和非方法“Microsoft.Office.Interop.Word.DocumentEvents2\u Event.Close”之间存在歧义。使用方法组
问题是有一个方法Close()和一个事件Close 看。正如海报上所说,您可能希望使用方法Close()而不是事件。在本例中,尝试将
word.ActiveDocument
强制转换为\u Document
,并对其调用Close()
编辑:您还可以将类型设置为
\u Application
,而不是Application
:
Microsoft.Office.Interop.Word._Application word = new Microsoft.Office.Interop.Word.Application();
(请注意,我目前无法对此进行测试,因为我当前的计算机上没有安装office)为什么要使用word.ActiveDocument.Close();?你不能直接调用document.Close(true);?另外,你没有破坏你的COM对象,你应该调用Marshal.ReleaseComObject(object)on document等等…给我同样的错误,而且它在Final part thingy中找不到引用。如果你搜索错误消息,这个问题有一些重复。顺便说一句:哦,对不起。我的错。谷歌搜索,但找不到错误/对不起,这个词对我来说是新的。你能把代码打出来吗?;$。我添加了一个更整洁的解决方案(尽管不幸的是未经测试)。我现在休息一下,我已经为这个错误挣扎了大约2个小时。我过会儿再打给你。不过还是要谢谢你!:)好了,它现在起作用了!但现在它抛出以下错误:comexception在代码处未处理:var document=word.Documents.Open(srcFile.FullName);
Microsoft.Office.Interop.Word._Application word = new Microsoft.Office.Interop.Word.Application();