Getting started

edit

Install the package

Add the Meziantou.Framework.TextDiff package to a project:

dotnet package add Meziantou.Framework.TextDiff

The examples of this documentation omit the using directives: they need using Meziantou.Framework;.

Compare two texts

TextDiff.ComputeDiff compares two texts line by line:

var oldText = "line1\nline2\nline3";
var newText = "line1\nline2 updated\nline3";

var result = TextDiff.ComputeDiff(oldText, newText);

Assert.True(result.HasDifferences);
Assert.Equal(
    [
        new TextDiffEntry(TextDiffOperation.Equal, "line1\n"),
        new TextDiffEntry(TextDiffOperation.Delete, "line2\n"),
        new TextDiffEntry(TextDiffOperation.Insert, "line2 updated\n"),
        new TextDiffEntry(TextDiffOperation.Equal, "line3"),
    ],
    result.Entries);
  • HasDifferences tells whether the texts differ.
  • Entries holds every line of both texts, in order, with what happened to it. The second line changed: a change is the deletion of the old line followed by the insertion of the new one.
  • Each line keeps its line terminator (\n here), so the entries concatenate back to the texts. The last line of the texts has none.

Compare words or characters

The comparison works on chunks, which are lines by default. To find the changed words or characters, set Chunker to TextChunker.Words or TextChunker.Characters; the other options ignore the casing, the whitespace and the line terminators:

var options = new TextDiffOptions
{
    Chunker = TextChunker.Words,        // Lines (default), Words, Characters, or custom chunker
    IgnoreCase = true,
    IgnoreWhitespace = true,
    IgnoreEndOfLine = true,
};

var result = TextDiff.ComputeDiff("Hello   world\r\n", "hello world\n", options);
Assert.False(result.HasDifferences);

See Chunking and Comparison options.

Next steps