UnifiedDiff Class

Writes, reads and applies diffs in the unified format of diff -u and git diff.

public static class UnifiedDiff

Methods

NameDescription
Apply(string, string)Applies a unified diff that holds one file to text.
Create(string, string, UnifiedDiffOptions?, CancellationToken)Compares oldText and newText line by line and returns the result as a unified diff.
Parse(string)Reads the files of a unified diff, such as the output of diff -u or git diff.

Apply(string, string)

UnifiedDiff.cs

Applies a unified diff that holds one file to text.

public static string Apply(string text, string patch)

Parameters

text string
The text to patch.
patch string
The text of the diff.

Returns

string The patched text.

Exceptions

ArgumentNullException
text or patch is null.
ArgumentException
patch does not hold exactly one file.
FormatException
patch is malformed.
UnifiedDiffApplyException
A hunk does not match the text.

Remarks

See UnifiedDiffFile.Apply for how the hunks are matched.

Create(string, string, UnifiedDiffOptions?, CancellationToken)

UnifiedDiff.cs

Compares oldText and newText line by line and returns the result as a unified diff.

public static UnifiedDiffFile Create(string oldText, string newText, UnifiedDiffOptions? options = null, CancellationToken cancellationToken = default)

Parameters

oldText string
The original text.
newText string
The modified text.
options UnifiedDiffOptions?
The file names, the number of lines of context and the algorithm.
cancellationToken CancellationToken
The token to monitor for cancellation requests.

Returns

UnifiedDiffFile The diff. Call UnifiedDiffFile.ToString to write it.

Exceptions

ArgumentNullException
oldText or newText is null.
ArgumentOutOfRangeException
An option of options is out of range.
OperationCanceledException
cancellationToken is canceled.

Remarks

Lines are separated by "\n" only, as diff does: a "\r" before it is part of the line, so the diff applies to the old text exactly. The comparison is ordinal.

Parse(string)

UnifiedDiff.cs

Reads the files of a unified diff, such as the output of diff -u or git diff.

public static IReadOnlyList<UnifiedDiffFile> Parse(string patch)

Parameters

patch string
The text of the diff.

Returns

IReadOnlyList<UnifiedDiffFile> The files of the diff, in order. A --- line followed by a +++ line starts a file.

Exceptions

ArgumentNullException
patch is null.
FormatException
A hunk is malformed: an invalid @@ line, a line with an unknown prefix, or fewer lines than its header gives.

Remarks

The lines outside the files, such as the diff --git and index lines of git, are ignored. The text after a tab in a --- or +++ line, a timestamp, is not part of the name. Binary patches and the renames and modes of git are not read.