我正在尝试比较两个不同的文本文件,并在新文件中写入不同的行。到目前为止,我已经写下了两个文件之间的差异,我想知道我需要添加到代码中的内容,以便我也可以编写这些行。例如:
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
您不能使用此操作,因为它返回diffs仅无视行索引。您必须迭代线条。
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>();
//previously, it was omitting the last line because of '<' so changed it to '<='
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);
}
我只会通过集合迭代并删除'_'条目。
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));
}