dotnet add package RecursiveAI.OneDiffRequires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
using OneDiff; var lines = Diff.Lines( File.ReadAllText("before.txt"), File.ReadAllText("after.txt")).Lines; var add = lines.Where(x => x.OldLine is null); var del = lines.Where(x => x.NewLine is null); Console.WriteLine("Added: " + string.Join(',', add.Select(x => x.NewLine))); Console.WriteLine("Removed: " + string.Join( ',', del.Select(x => x.OldLine)));
Unzip the example, then dotnet run.
Prints the added and removed line numbers:
Added: 3 Removed: 2
Both input files are in the download. Here’s before.txt:
Start Draft Review End
And after.txt:
Start Review Publish End
Review moved up a row after Draft was deleted, but its text didn’t change, so it isn’t listed. Run from the unzipped project directory: a missing input file causes File.ReadAllText to throw FileNotFoundException.
Variations
Add the changed text to each annotation. Replace the code after the lines declaration. Use the old line number for a deletion and the new line number for an insertion.
foreach (var line in lines) { if (line.Kind == EditKind.Delete) Console.WriteLine($"-{line.OldLine}: {line.Text}"); if (line.Kind == EditKind.Insert) Console.WriteLine($"+{line.NewLine}: {line.Text}"); }
-2: Draft +3: Publish
Related recipes
The short answer
Read the files as text, call Diff.Lines(before, after), then filter its Lines view. An insertion has no OldLine, so take NewLine; a deletion has no NewLine, so take OldLine. You can also filter by EditKind.Insert and EditKind.Delete, as the annotation example does. Both sets of numbers start at 1. Keep them separate: line 3 of the new file and line 3 of the old file need not describe the same text. The line number on the missing side is null, not zero.
How do you find different lines in two files?
Compare the sequences of lines, not two arrays at matching indexes. In the example, the old line 2 is Draft and the new line 2 is Review. Comparing the files by index would flag that row, and it would flag row 3 too, where the old file has Review and the new one has Publish. The line diff instead matches the two occurrences of Review and identifies the actual deletion and insertion around it.
To annotate a review, attach added numbers to the new file and removed numbers to the old file. A replacement appears as a deletion plus an insertion in this view. Don’t pair the two lists by index: a block can have unequal numbers of removals and additions. If you want a visual alignment instead of annotations keyed to file lines, the side-by-side view pairs deletions and insertions within a changed block.
The line view drops line breaks from each returned Text value. It still counts an unterminated final line as a line. Start with Diff.Lines, not Diff.Words, for a line-number list: a word diff can return several entries with the same line number because it tracks edits within a line.