欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 如何判断两个文件内容是否相同的方法

程序员文章站 2023-12-18 23:12:28
该哈希算法为一个文件生成一个小的二进制“指纹”,从统计学的角度来看,不同的文件不可能生成相同的哈希码 要生成一个哈希码,必须首先创建一个hashalgorithm对象,通...

该哈希算法为一个文件生成一个小的二进制“指纹”,从统计学的角度来看,不同的文件不可能生成相同的哈希码

要生成一个哈希码,必须首先创建一个hashalgorithm对象,通过hashalgorithm.create方法来完成。然后调用

hashalgorithm.computehash方法,它会返回一个存储哈希码的字节数组,再使用bitconverter.tostring()将其

装换为字符串进行比较。

源码如下:

复制代码 代码如下:

public static bool isvalidfilecontent(string filepath1, string filepath2)
       {
           //创建一个哈希算法对象
           using (hashalgorithm hash = hashalgorithm.create())
           {
               using (filestream file1 = new filestream(filepath1, filemode.open),file2=new filestream(filepath2,filemode.open))
               {
                   byte[] hashbyte1 = hash.computehash(file1);//哈希算法根据文本得到哈希码的字节数组
                   byte[] hashbyte2 = hash.computehash(file2);
                   string str1 = bitconverter.tostring(hashbyte1);//将字节数组装换为字符串
                   string str2 = bitconverter.tostring(hashbyte2);
                   return (str1==str2);//比较哈希码
               }
           }
       }

使用该函数的主函数

复制代码 代码如下:

static void main(string[] args)
     {
         string filepath1 = @"f:/1.txt";
         string filepath2 = @"f:/2.txt";
         bool valid=isvalidfilecontent(filepath1, filepath2);
         console.writeline(valid.tostring());
         console.readkey();
     }

上一篇:

下一篇: