Microsoft Interop Word:C#下.doc与.docx文档对比异常问题排查
嘿,这个跨格式Word对比的问题我之前也碰到过,来给你捋捋怎么解决!
解决跨格式(.doc与.docx)Word文档对比失败的问题
问题根源
当你打开.doc格式的文档时,Word默认会进入兼容模式,这种模式下Word会禁用部分新功能(包括完整的文档对比逻辑),导致跨格式对比时无法正常执行。所以核心思路是让两个文档处于相同的格式(优先.docx)再进行对比。
解决方案:先转换格式再对比
我们可以先把.doc文件临时转换为.docx,再用两个.docx文档执行对比,这样就能避开兼容模式的限制。下面是具体的代码修改方案:
1. 添加格式转换辅助方法
这个方法会把.doc文件转换成临时的.docx文件,对比完成后再删除临时文件:
private string ConvertDocToDocx(string docFilePath) { // 生成临时docx路径,存在系统临时目录里 string tempDocxPath = Path.Combine(Path.GetTempPath(), $"{Path.GetFileNameWithoutExtension(docFilePath)}_converted.docx"); object docFile = docFilePath; object saveAsPath = tempDocxPath; // 指定保存为docx格式 object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument; // 以只读模式打开原doc,避免锁定文件 Word.Document tempDoc = wordApp.Documents.Open(ref docFile, ReadOnly: true); tempDoc.SaveAs(ref saveAsPath, ref fileFormat); tempDoc.Close(); return tempDocxPath; }
2. 修改对比逻辑,先转换再对比
调整你的主逻辑,先检查文件格式,转换.doc后再执行对比:
string rutaVersion1 = "你的第一个文件路径"; string rutaVersion2 = "你的第二个文件路径"; Word.Application wordApp = new Word.Application(); Word.Document doc1 = null; Word.Document doc2 = null; string tempFile1 = rutaVersion1; string tempFile2 = rutaVersion2; try { // 检查并转换.doc文件 if (rutaVersion1.ToLower().EndsWith(".doc")) tempFile1 = ConvertDocToDocx(rutaVersion1); if (rutaVersion2.ToLower().EndsWith(".doc")) tempFile2 = ConvertDocToDocx(rutaVersion2); // 打开转换后的文档(都是docx,不会进入兼容模式) doc1 = wordApp.Documents.Open(tempFile1, Visible: true); // 对比用的第二个文档可以隐藏,避免弹窗干扰 doc2 = wordApp.Documents.Open(tempFile2, Visible: false); // 执行对比操作,这里用Word原生的Compare方法比手动开跟踪修订更可靠 doc1.Compare( Name: tempFile2, CompareTarget: Word.WdCompareTarget.wdCompareTargetNew, DetectFormatChanges: true, IgnoreAllComparisonWarnings: true ); // 开启修订显示,方便查看差异 doc1.TrackRevisions = true; doc1.ShowRevisions = true; } catch (Exception ex) { Console.WriteLine($"对比过程出错:{ex.Message}"); } finally { // 清理资源,关闭Word文档和进程 if (doc1 != null) doc1.Close(SaveChanges: false); if (doc2 != null) doc2.Close(SaveChanges: false); if (wordApp != null) wordApp.Quit(); // 删除临时转换的文件,避免占用空间 if (tempFile1 != rutaVersion1 && File.Exists(tempFile1)) File.Delete(tempFile1); if (tempFile2 != rutaVersion2 && File.Exists(tempFile2)) File.Delete(tempFile2); }
额外注意事项
- 确保你引用的是对应Office版本的
Microsoft.Office.Interop.Word程序集,版本不匹配可能导致异常。 - 临时文件存放在系统临时目录,要确保程序有读写该目录的权限。
- 对比完成后一定要清理Word进程,不然会有后台残留的WINWORD.exe进程占用资源。
内容的提问来源于stack exchange,提问作者Rubén M
相关产品推荐
相关产品推荐

