Compare two text files line by line
37,025
Solution 1
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);
Solution 2
Since your question seems like you made no effort whatsoever I'll give you just a rough outline.
- Read both files line by line, e.g. with
File.ReadAllLines
orFile.ReadLines
. - Use LINQ's
Except
method. - Write the results into a new file.
Author by
Developman
Updated on July 09, 2022Comments
-
Developman almost 2 years
Beneath here i described a example Scenario:
"FileA-Database.txt" contains the following names:
KB200
KB300
KB400
"FileB-Slave.txt" contains the following names:
KB600
KB200
KB400
KB700
I want to compare the "FileA-Database.txt" with "FileB-Slave.txt" and let the missing values be filled in automatically in the "FileA-Database.txt" file also i need to display the missing values in a text file called "Results.txt".
The code needs to be compatible with C# (framework 4.0+) please!.
I need a simple approach, mine doesnt work exactly the way i want it to:
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 }
-
Developman over 11 yearsI am trying, i need a simple approach... Posted what i have done :p
-
Sergey Kulgan about 8 yearsIt is not standard comparison due files will be considered the same if the same set of lines has different sequence.
-
Angelo over 7 yearsi know this is an old question, but how will you deal with large files for example 1 gig or more? i tried this answer and ended up out of memory exception..
-
null about 7 years@Angelo did you ever find anything?
-
Tommaso Belluzzo about 7 yearsYou could try the following: Enumerable<String> onlyB = linesB.AsParallel().Except(linesA.AsParallel());