asddasd

导航

C#比较两文件内容是否完全一样

C#比较两文件内容是否完全一样

————————————————

原文链接:https://blog.csdn.net/csdn_zhangchunfeng/article/details/81093196

一.逐一比较字节数

private bool CompareFile(string firstFile, string secondFile)
{
if (!File.Exists(firstFile) || !File.Exists(secondFile)) {
return false;
}
if (firstFile == secondFile) {
return true;
}
int firstFileByte = 0;
int secondFileByte = 0;
FileStream secondFileStream = new FileStream(secondFile, FileMode.Open);
FileStream firstFileStream = new FileStream(firstFile, FileMode.Open);
if (firstFileStream.Length != secondFileStream.Length) {
firstFileStream.Close();
secondFileStream.Close();
return false;
}
do
{
firstFileByte = firstFileStream.ReadByte();
secondFileByte = secondFileStream.ReadByte();
} while ((firstFileByte == secondFileByte) && (firstFileByte != -1)) ;
firstFileStream.Close();
secondFileStream.Close();
return (firstFileByte == secondFileByte);
}
二.逐行比较内容

private bool CompareFileEx(string firstFile, string secondFile)
{
if (!File.Exists(firstFile) || !File.Exists(secondFile)) {
return false;
}
if (firstFile == secondFile) {
return true;
}
string firstFileLine = string.Empty;
string secondFileLine = string.Empty;
StreamReader secondFileStream = new StreamReader(secondFile, Encoding.Default);
StreamReader firstFileStream = new StreamReader(firstFile, Encoding.Default);
do
{
firstFileLine = firstFileStream.ReadLine();
secondFileLine = secondFileStream.ReadLine();
} while ((firstFileLine == secondFileLine) && (firstFileLine != null));
firstFileStream.Close();
secondFileStream.Close();
return (firstFileLine == secondFileLine);
}
三.比较哈希码

private bool CompareFileExEx(string firstFile, string secondFile)
{
if (!File.Exists(firstFile) || !File.Exists(secondFile)) {
return false;
}
if (firstFile == secondFile) {
return true;
}
using (HashAlgorithm hash = HashAlgorithm.Create())
{
using (FileStream firstStream = new FileStream(firstFile, FileMode.Open),
secondStream = new FileStream(secondFile, FileMode.Open))
{
byte[] firstHashByte = hash.ComputeHash(firstStream);
byte[] secondHashByte = hash.ComputeHash(secondStream);
string firstString = BitConverter.ToString(firstHashByte);
string secondString = BitConverter.ToString(secondHashByte);
return (firstString == secondString);
}
}
}
三种方法各有利弊,可根据具体情况具体分析,欢迎大家提出建议。

posted on 2020-03-17 21:16  asddasd  阅读(421)  评论(0编辑  收藏  举报