我有两个文本文件output1
和output2
output1包含以下内容:
USA
New Zealand
Switzerland
Nigeria
Australia
Brazil
Kenya
Mexico
output2包含
USA
Switzerland
Nigeria
Australia
Brazil
Mexico
China
Pakistan
然后我将同时检查output1和output2并将差异写入新的文本文件中
The file - New Zealand - is in output1 but not in output2
The file - Kenya - is in output1 but not in output2
The file - China - is in output2 but not in output1
The file - Pakistan - is in output2 but not in output1
这是我为第一个输出文件编写的代码,并为第二个输出文件重复了
public void runCMD(string path1, string path2)
{
//path 1 should be the directory you are trying to get the files from.
//path 2 should be the directory you want to save result.txt to.
path2 = "C:/users/dan/desktop/";
System.Diagnostics.Process process = new
System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new
System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle =
System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C dir /s/b " + path1 + " > C:/users/dan/desktop/result_0.txt";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
//the goal here is to remove the path from every filename
string line;
System.IO.StreamWriter replace = new System.IO.StreamWriter(@"C:/users/dan/desktop/output1.txt");
System.IO.StreamReader file = new System.IO.StreamReader(@"C:/users/dan/desktop/output_0.txt");
while ((line = file.ReadLine()) != null)
{
//line = System.IO.Path.GetFileName(line);
line = System.IO.Path.GetFileName(line);
replace.WriteLine(System.IO.Path.GetFileName(line));
//Console.WriteLine(line);
}
replace.Close();
file.Close();
File.Delete(@"C:/users/dan/desktop/output_0.txt");
}
我的问题是如何比较两个文件?
答案 0 :(得分:0)
您可以尝试使用File.ReadAllLines
读取文件,然后使用HashSet
获得与Enumerable.Except
的区别:
public void FileDifference(string path1, string path2)
{
var firstOutput = File.ReadAllLines(path1).ToHashSet();
var secondOutput = File.ReadAllLines(path2).ToHashSet();
foreach (var line in firstOutput.Except(secondOutput))
{
Console.WriteLine($"The file - {line} - is in output1 but not in output2");
}
foreach (var line in secondOutput.Except(firstOutput))
{
Console.WriteLine($"The file - {line} - is in output2 but not in output1");
}
}
您可以这样打电话:
FileDifference(@"YOUR_PATH\output1.txt", @"YOUR_PATH\output2.txt");
输出:
The file - New Zealand - is in output1 but not in output2
The file - Kenya - is in output1 but not in output2
The file - China - is in output2 but not in output1
The file - Pakistan - is in output2 but not in output1
答案 1 :(得分:0)