xhbIBC 发表于 2013-9-11 14:52:50

.NET实现word在线对比

请问.NET实现word在线对比,就是调用office的比较功能,怎么实现呢?

ibcadmin 发表于 2013-9-11 15:46:44

比较两个文件的内容是否完全相同。这里将程序代码列示如下:
protected void btnGoToCompare_Click(object sender, EventArgs e)
    {
      string file1 =HttpContext.Current.Request.MapPath("~/1.txt");//第一个文件的名称
      string file2 = HttpContext.Current.Request.MapPath( "~/2.txt");//第二个文件的名称
      string script = "";
      if (FileCompare(file1, file2))
      {
         script="alert('两个文件是相同的。')";
         this.Page.ClientScript.RegisterStartupScript(GetType(),Guid.NewGuid().ToString(),script,true);
      }
      else
      {
            script = "alert('两个文件是不相同的。')";
            this.Page.ClientScript.RegisterStartupScript(GetType(), Guid.NewGuid().ToString(), script, true);
      }
    }

    //此方法所接收的两个字符串代表您所要比较的两个文件。如果两个文件的内容完全相同,
    //将返回 True;任何其他的返回值都表示这两个文件的内容有所差异。
    private bool FileCompare(string file1, string file2)
    {
      //判断相同的文件是否被参考两次。
      if (file1 == file2)
      {
            return true;
      }
      int file1byte = 0;
      int file2byte = 0;
      FileStream fs2 = new FileStream(file2, FileMode.Open);
      using (FileStream fs1 = new FileStream(file1, FileMode.Open))
      {
            //检查文件大小。如果两个文件的大小并不相同,则视为不相同。
            if (fs1.Length != fs2.Length)
            {
                // 关闭文件。
                fs1.Close();
                fs2.Close();
                return false;
            }
            //逐一比较两个文件的每一个字节,直到发现不相符或已到达文件尾端为止。
            do
            {
                // 从每一个文件读取一个字节。
                file1byte = fs1.ReadByte();
                file2byte = fs2.ReadByte();
            }while ((file1byte == file2byte) && (file1byte != -1));
            // 关闭文件。
            fs1.Close();
            fs2.Close();
      }
      //返回比较的结果。在这个时候,只有当两个文件的内容完全相同时,"file1byte" 才会等于 "file2byte";
      return ((file1byte - file2byte) == 0);
    }

页: [1]
查看完整版本: .NET实现word在线对比