C#比较两个文本文件的内容是否相等

本文展示了一段使用C#进行文件哈希值比较的代码示例,通过创建FileStream读取文件并使用HashAlgorithm计算两个文件的哈希值,最后将字节数组转换为字符串形式进行比较,以判断文件是否相同。

1.引用:using System.IO;

2.代码:

class Program
{
static void Main(string[] args)
{
string filePath1 = "F:\\测试文件\\11.txt";
string filePath2 = "F:\\测试文件\\22.txt";
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);
if (str1 == str2)
{

Console.WriteLine("相同");

}
else
{

Console.WriteLine("不同");

}
}
Console.ReadKey();
}
}

}

 

转载于:https://www.cnblogs.com/nn1314/p/10489165.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值