分享

.NET实现word在线对比

 mybook564 2013-09-24
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);
   }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多