Recursive AI

Apply a multi-file unified patch safely in C#

OneDiff is a free, open-source diff library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Apply changes.diff from the zip to known text in memory. This example accepts text hunks, not Git metadata.

Terminal
dotnet add package RecursiveAI.OneDiff

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneDiff.Patching;
 
var names = StringComparer.Ordinal;
var originals =
    new Dictionary<string, string>(names)
{
    ["schedule.txt"] = "Monday\n",
    ["contact.txt"] = "Sales\n",
};
 
var text =
    File.ReadAllText("changes.diff");
var patch = UnifiedPatch.Parse(text);
if (patch.Files.Count == 0 ||
    patch.ToString() != text)
    throw new InvalidDataException(
        "Expected only canonical text hunks.");
 
var staged = new Dictionary<string, string>(
    originals, names);
var seen = new HashSet<string>(names);
var exact = new UnifiedApplyOptions
{
    MaxFuzz = 0, MaxOffset = 0
};
foreach (var file in patch.Files)
{
    var name = file.OldName;
    if (name != file.NewName ||
        file.Hunks.Count == 0 ||
        file.ExtendedHeader.Count != 0 ||
        !seen.Add(name) ||
        !originals.TryGetValue(name,
            out var original))
        throw new InvalidDataException(
            "Unsupported or unlisted file.");
 
    var result = file.Apply(original, exact);
    if (!result.Success)
        throw new InvalidDataException(
            $"Patch conflict: {name}");
    staged[name] = result.Text;
}
 
originals = staged;
foreach (var (name, value) in originals)
    Console.Write($"{name}: {value}");

changes.diff contains two edits. Save it with LF line endings and a final newline if you’re creating it yourself:

DIFF
--- schedule.txt
+++ schedule.txt
@@ -1 +1 @@
-Monday
+Friday
--- contact.txt
+++ contact.txt
@@ -1 +1 @@
-Sales
+Support

dotnet run prints:

Text
schedule.txt: Friday
contact.txt: Support

A malformed patch throws PatchFormatException; an unsupported file or a rejected hunk causes this program to throw InvalidDataException before replacing originals. The only file read is the fixed changes.diff path; neither header is ever used to open or write a file.

Unzip the example, then dotnet run.

Updates the two in-memory strings, not the files on disk.

Variations

Try a conflict in the second file. Replace the line that reads changes.diff with the snippet below. It fails with Patch conflict: contact.txt; the staged schedule edit never reaches originals.

C#
var text = File.ReadAllText("changes.diff")
    .Replace("-Sales", "-Billing");

Reject a name outside the allowlist. Replace the same line with this snippet. It fails with Unsupported or unlisted file.

C#
var text = File.ReadAllText("changes.diff")
    .Replace("schedule.txt", "../schedule.txt");

Reject a patch containing binary data. This variation adds a section after the valid text hunks. Parsing alone skips it; the round-trip comparison rejects the complete input with Expected only canonical text hunks.

C#
var text = File.ReadAllText("changes.diff")
    + "diff --git a/logo.png b/logo.png\n"
    + "Binary files a/logo.png and b/logo.png differ\n";

Update the allowlisted files on disk. In a trusted working directory, create schedule.txt containing Monday and contact.txt containing Sales, each ending with a newline. Replace the originals declaration with these reads. The names are fixed here, not taken from the patch.

C#
var originals = new Dictionary<string, string>(names)
{
    ["schedule.txt"] = File.ReadAllText("schedule.txt"),
    ["contact.txt"] = File.ReadAllText("contact.txt"),
};

Just before originals = staged;, add this loop. It writes each changed file to a temporary file in the same directory and renames it over the original only after all hunks have passed. It replaces files one at a time, not as an all-or-nothing disk update.

C#
foreach (var name in seen)
{
    var target = Path.GetFullPath(name);
    var temp = Path.Combine(Path.GetDirectoryName(target)!,
        Path.GetRandomFileName());
    var stream = new FileStream(temp, FileMode.CreateNew);
    try
    {
        using (stream)
        using (var writer = new StreamWriter(stream))
            writer.Write(staged[name]);
        File.Move(temp, target, overwrite: true);
    }
    finally
    {
        File.Delete(temp);
    }
}

The short answer

Parse the patch with UnifiedPatch.Parse and use each section’s old and new names only as keys into an explicit allowlist. Apply each file patch to its original text and check Success. Keep the edited strings apart from the originals until the last file passes. That separation makes a conflict in the final file an all-or-nothing decision for the in-memory snapshot.

What does a unified diff file look like?

Each text section starts with --- for the original name and +++ for the revised name. A hunk is a contiguous group of changes and nearby context. Its @@ header gives the old and new line ranges. Below it, - marks a removed line, + an added line, and a leading space an unchanged context line. A patch for more than one file has another header pair after the last hunk for the previous file. These names identify text to patch; the headers don’t authorize filesystem changes.

How do you apply a diff patch without partially updating files?

The OneDiff parser can skip text outside supported hunks, including binary and rename-only sections. In this example, accepting only text that exactly matches the parsed patch’s serialized form catches skipped material. A separate check disallows extended headers and requires each header pair to name the same allowlisted file exactly once. This deliberately rejects some valid unified diffs whose formatting differs from OneDiff’s serialization; it is not a general Git patch importer.

OneDiff normally tries other positions when a hunk fails at its stated line and can drop context from the match. MaxOffset = 0 and MaxFuzz = 0 turn those behaviors off here. A successful parse still doesn’t tell you if the original text matches: check every Apply result before using any staged text. A patch already applied to a file can also return a rejected hunk, not success.

The code swaps a dictionary reference after all checks pass. It does not make a batch of disk writes atomic. If you need persistent all-or-nothing updates, put the final publish step behind a storage transaction; a loop of separate writes can still stop halfway through.

All onediff recipes