在这下面我描述了一个示例场景:
“FileA-Database.txt”包含以下名称:
KB200
KB300
KB400
“FileB-Slave.txt”包含以下名称:
KB600
KB200
KB400
KB700
我想将“FileA-Database.txt”与“FileB-Slave.txt”进行比较,并在“FileA-Database.txt”文件中自动填写缺失值,同时我需要显示缺失的值在名为“Results.txt”的文本文件中。
代码需要与C#(框架4.0+)兼容!
我需要一个简单的方法,我的工作方式与我想要的完全不同:
private void button_compare_Click(object sender, EventArgs e)
{
string fileA, fileB, fileC;
fileA = "database-critical.txt";
fileB = "patchlist.txt";
fileC = "result.txt";
string alphaFilePath = fileA;
List<string> alphaFileContent = new List<string>();
using (FileStream fs = new FileStream(alphaFilePath, FileMode.Open))
using(StreamReader rdr = new StreamReader(fs))
{
while(!rdr.EndOfStream)
{
alphaFileContent.Add(rdr.ReadLine());
}
}
string betaFilePath = fileB;
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(betaFilePath, FileMode.Open))
using (StreamReader rdr = new StreamReader(fs))
{
while(! rdr.EndOfStream)
{
string[] betaFileLine = rdr.ReadLine().Split(Convert.ToChar(","));
if (alphaFileContent.Contains(betaFileLine[0]))
{
sb.AppendLine(String.Format("{0}", betaFileLine[0]));
}
}
}
using (FileStream fs = new FileStream(fileC, FileMode.Create))
using (StreamWriter writer = new StreamWriter(fs))
{
writer.Write(sb.ToString());
}
}
//End
}
答案 0 :(得分:28)
String directory = @"C:\Whatever\";
String[] linesA = File.ReadAllLines(Path.Combine(directory, "FileA-Database.txt"));
String[] linesB = File.ReadAllLines(Path.Combine(directory, "FileB-Database.txt"));
IEnumerable<String> onlyB = linesB.Except(linesA);
File.WriteAllLines(Path.Combine(directory, "Result.txt"), onlyB);
答案 1 :(得分:9)
既然你的问题似乎没有做出任何努力,我会给你一个粗略的轮廓。
File.ReadAllLines
或File.ReadLines
。Except
方法。