我想比较两个word文档,我在网上找到了一个使用c#比较word文档的解决方案。执行代码时,它会打开三个应用程序(原始文档、需要比较的文档和显示结果的第三个文档)。有没有办法让这三个应用程序不打开,而是向控制台返回布尔值?
objective: Display the comparison of the two documents in a console application as either 'the same' or 'different'
using System;
using System.IO;
using Microsoft.Office.Interop.Word;
class Program
{
static void Main()
{
Application wordApp = new Application();
wordApp.Visible = true;
object wordTrue = (object)true;
object wordFalse = (object)false;
object fileToOpen = @"C:doc1.docx";
object missing = Type.Missing;
Document doc1 = wordApp.Documents.Open(ref fileToOpen,
ref missing, ref wordFalse, ref wordFalse, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref wordTrue, ref missing,
ref missing, ref missing, ref missing);
object fileToOpen1 = @"C:doc2.docx";
Document doc2 = wordApp.Documents.Open(ref fileToOpen1,
ref missing, ref wordFalse, ref wordFalse, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
Document doc = wordApp.CompareDocuments(doc1, doc2, WdCompareDestination.wdCompareDestinationNew, WdGranularity.wdGranularityWordLevel,
true, true, true, true, true, true, true, true, true, true, "", true);
//Something like the following:
if (doc1 != doc2)
{
Console.WriteLine("They are not same");
}
else
{
Console.WriteLine("They are identical");
}
Console.ReadKey();}}
您尝试过设置Visible=false吗?我想这就是为什么你的word文档会弹出的原因。我过去做过一些word文档操作,通过将visible属性设置为false,您可以在不显示文档的情况下使用文档。(winword.exe无论如何都会执行)
您的代码使用像Microsoft.Office.Interop.Word
这样的互操作,因此您可以使用隐藏窗口
wordApp.Visible = false;
最后:
wordApp.Quit();
然而,一种更快的方法是以字节为单位读取它们。您可以比较这两个字节数组以了解它们的相似程度。