比较两个文本文件之间的差异,并注意C#中不同的行

时间:2017-06-27 19:08:38

标签: c# visual-studio text compare

我试图比较两个不同的文本文件,并在新文件中写入不同的行。到目前为止,我写了两个文件之间的差异,我想知道我需要添加到代码中,所以我也可以编写这些行。例如:

text1:
 a
 bc
 d
 _
 f

text2:
 a
 bcd
 d
 e
 _

我的代码输出的内容是:

_
d
_
e
f

我想要的是:

line 2: d
line 4: e
line 5: f

希望这是有道理的,这是我的代码:

private void button_compare_Click(object sender, EventArgs e)
{

    String directory = @"C:\.......\";
    String[] linesA = File.ReadAllLines(Path.Combine(directory, "test1.txt"));
    String[] linesB = File.ReadAllLines(Path.Combine(directory, "test2.txt"));

    IEnumerable<String> onlyB = linesB.Except(linesA);

    File.WriteAllLines(Path.Combine(directory, "Result2.txt"), onlyB);
}

修改 我想出了我最初的问题,感谢下面回复的优秀人才。出于好奇,我想更进一步...... 假设每个文件中的随机行与一个单词不同。例如: text1: line 3: hello how are you

text2: line 3: hi how are you

你会怎么做才能使输出文件只包含已更改的单词?例如

output file: line 3: hello

2 个答案:

答案 0 :(得分:0)

我只是遍历集合并删除'_'条目。

for (int i = 0; i < onlyB.Count(); i++) // go through every element in the collection
{
    string line = onlyB.ElementAt(i); // get the current element at index i
    if (line == "_") continue; // if the element is a '_', ignore it

    // write to the console, or however you want to output.
    Console.WriteLine(string.Format("line {0}: {1}", i, line));
}

答案 1 :(得分:0)

除了之外,你不能这样做,因为它只返回差异而忽略行索引。你必须迭代这些线。

 private void button_compare_Click(object sender, EventArgs e)
 {
       String directory = @"C:\.......\";
       String[] linesA = File.ReadAllLines(Path.Combine(directory, "test1.txt"));
       String[] linesB = File.ReadAllLines(Path.Combine(directory, "test2.txt"));

       List<string> onlyB = new List<string>();

       for (int i = 0; i < linesA.Length; i++)
       {
          if (!linesA[i].Equals(linesB[i])) 
          {
             onlyB.Add("line " + i + ": " + string.Join(" ",linesB[i].Split(' ').Except(linesA[i].Split(' '))));
          }
       }

       File.WriteAllLines(Path.Combine(directory, "Result2.txt"), onlyB);
  }