比较两个文本文件并显示什么是相同的

时间:2017-03-21 20:15:08

标签: c# visual-studio compare stringcomparer

我在比较两个文件时需要帮助。我能够打印出两者之间的区别,但我无法弄清楚如何在两者错误时打印两者之间的相同内容。任何人都可以帮我吗?提前谢谢!

    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            //Reads files line by line
            var fileOld = File.ReadLines(Old);
            var fileNew = File.ReadLines(New);                              //Ignores cases in files
            IEnumerable<String> OldTxt = fileOld.Except(fileNew, StringComparer.OrdinalIgnoreCase);
            IEnumerable<String> NewTxt = fileNew.Except(fileOld, StringComparer.OrdinalIgnoreCase);

            FileCompare compare = new FileCompare();

            bool areSame = OldTxt.SequenceEqual(NewTxt);

            if (areSame == true)
            {
                MessageBox.Show("They match!");
            }
            else if(areSame == false)
            {
                // Find the set difference between the two files.  
                // Print to Not Equal.txt
                var difFromNew = (from file in OldTxt
                                  select file).Except(NewTxt);

                using (var file = new StreamWriter(NotEqual))
                {
                    foreach (var notEq in difFromNew)
                    {
                        file.WriteLine(notEq.ToString() + "\n", true);
                    }
                }

                MessageBox.Show("They are not the same! Please look at 'Not Equal.txt' to see the difference. Look at 'Equal.txt' to see what is the same at this time.");
            }

        }
        catch
        {
            MessageBox.Show("'NewConvert.txt' or 'OldConvert.txt' files does not exist.");
        }

    }

1 个答案:

答案 0 :(得分:1)

首先,我认为您的代码中可能存在错误。 'fileOld'包含旧文件的所有内容,'OldTxt'仅包含新文件中不存在的旧文件文本。在我的回答之后,请参阅下面的一些代码清理想法。

我认为你正在寻找Intersect,它返回两个IEnumerables共有的项目:

var commonItems = fileOld.Intersect(fileNew);

或者,由于您已经有difFromNew中捕获的差异列表,因此您可以再次使用Except

var difFromNew = fileOld.Except(fileNew); // Note I fixed what I think is a bug here
var commonItems = fileOld.Except(difFromNew);

一些潜在的错误:

  1. SequenceEqual不仅意味着项目相同,而且它们的顺序相同。如果您关心订单,那么这是合适的。问题是这会使差异很难显示,因为您用来比较列表的其他方法(ExceptIntersect关心订单,只是否存在某个项目。因此,如果fileOld包含项cat | dogfileNew包含项dog | cat,那么它们将不相等,但您也无法显示差异({ {1}}将包含fileOld.Except(fileNew)个项目。
  2. 在您的0列表中,您正在使用diffFromNew,即旧文件中的唯一文本,并对{{1}执行OldTxt },这是新文件中的唯一文本。这两者之间不能重叠 - 事实上Except 默认情况下已包含 NewTxt
  3. 以下是获取您正在寻找的列表的一种方法:

    OldTxt

    以下是这些更改后代码的外观:

    diffFromNew
相关问题