有没有办法比较从2行(或第n行)开始的两个txt文件?我试图在线搜索但无法找到任何方式
我有很多例子来比较两个文件,但所有例子都与整个文件有关。
现在我正在使用以下代码
private static bool FileCompare(string file1, string file2)
{
int file1byte;
int file2byte;
FileStream fs1;
FileStream fs2;
if (file1 == file2)
{
return true;
}
fs1 = new FileStream(file1, FileMode.Open, FileAccess.Read);
fs2 = new FileStream(file2, FileMode.Open, FileAccess.Read);
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();
return ((file1byte - file2byte) == 0);
}
答案 0 :(得分:1)
我能想到实现这一点的最简单方法是使用File.ReadLines()
和一些Linq:
private static bool FileCompare(string file1, string file2, int offset = 0)
{
//Reads the lines, skips the "offset" number of lines
var file1Lines = File.ReadLines(file1).Skip(offset);
var file2Lines = File.ReadLines(file2).Skip(offset);
//gets two collections of the differences, ignoring case
var firstNotSecond = file1Lines.Except(file2Lines, StringComparer.OrdinalIgnoreCase);
var secondNotFirst = file2Lines.Except(file1Lines, StringComparer.OrdinalIgnoreCase);
//If there is nothing in both collections they are the same
return !firstNotSecond.Any() && !secondNotFirst.Any();
}
我今天学到了一些东西,@ AleksAndreev在评论中指出SequenceEqual()
存在。我的回答可能更简单:
private static bool FileCompareV2(string file1, string file2, int offset = 0)
{
//Reads the lines, skips the "offset" number of lines
var file1Lines = File.ReadLines(file1).Skip(offset);
var file2Lines = File.ReadLines(file2).Skip(offset);
return file1Lines.SequenceEqual(file2Lines, StringComparer.OrdinalIgnoreCase) &&
file2Lines.SequenceEqual(file1Lines, StringComparer.OrdinalIgnoreCase);
}
对于两种解决方案here
,略有改动的小提琴