C# 比较c中从第二行(第n行)开始的两个文件#

C# 比较c中从第二行(第n行)开始的两个文件#,c#,C#,有没有办法比较从第2行(或第n行)开始的两个txt文件?我试图在网上搜索,但找不到任何方法 我有很多例子来比较两个文件,但所有的例子都与整个文件有关 现在我正在使用以下代码 private static bool FileCompare(string file1, string file2) { int file1byte; int file2byte; FileStream fs1; FileStream fs2;

有没有办法比较从第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);
    }

我认为实现这一点的最简单方法是使用
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在评论中指出。我的回答可以更加简单:

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);
}

对两种解决方案都进行了轻微修改

Two Loop,Linq,有无限的可能性您甚至没有尝试比较您发布的代码中的行。
file1==file2
也不是最聪明的主意,它将进行区分大小写的比较。如果一条路径是小写的,另一条路径是大写的呢?另外,你的整个代码可以用三行或三行替换。对不起,我不明白你的代码与你想要实现的目标有什么关系。你检查过了吗?为什么不
file1Lines.SequenceEqual(file2Lines)
?@AleksAndreev我已经编辑了我的答案,包括
SequenceEqual()
,这是你的建议,但是如果你决定自己回答,我将从我的答案中删除该编辑。谢谢你的知识炸弹!