---
title: "Save and restore a pathfinding grid in C#"
url: https://recursiveai.org/onepath/cookbook/save-and-restore-grid-search-state/
description: "Serialize a C# pathfinding grid with OnePath, including its dimensions, cells, and terrain costs. Read it back and handle a truncated save."
version: "1.2.0"
---

# Save and restore a pathfinding grid in C#

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

[NuGet](https://www.nuget.org/packages/RecursiveAI.OnePath) · [GitHub](https://github.com/recursive-ai-oss/onepath-csharp) · [Docs](https://recursiveai.org/onepath/docs/) · [Download example (.zip)](https://recursiveai.org/onepath/cookbook/save-and-restore-grid-search-state/save-and-restore-grid-search-state.zip)

This saves the map, not a search in progress. To keep an unfinished search, see [Resume a search across ticks](https://recursiveai.org/onepath/cookbook/resume-path-search-across-ticks/). Here `.` is open, `2` is area 2, and `#` is a wall.

```shell
dotnet add package RecursiveAI.OnePath
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OnePath;

var map = Grid.FromText(".2.\n.#.");
map.Areas[2] = 5; // 5 per step within area 2
byte[] state = map.SaveState();
var copy = Grid.FromState(state);
Console.WriteLine(
    $"{copy.Width} x {copy.Height}");
Console.WriteLine(copy.Areas[2]);
```

```text
3 x 2
5
```

Unzip [the example](https://recursiveai.org/onepath/cookbook/save-and-restore-grid-search-state/save-and-restore-grid-search-state.zip), then `dotnet run`.

## The full program

The program saves the 3×2 grid to a byte array, reads it into a new grid, and prints the restored cells and terrain cost. Then it removes the last byte and tries to restore that incomplete snapshot.

```csharp
using RecursiveAI.OnePath;

var map = Grid.FromText(".2.\n.#.");
map.Areas[2] = 5;
byte[] state = map.SaveState();
var restored = Grid.FromState(state);
Console.WriteLine($"Dimensions: {restored.Width} x {restored.Height}");
Console.WriteLine($"Cell (1,0): area {restored.GetArea(1, 0)}");
Console.WriteLine($"Cell (1,1): area {restored.GetArea(1, 1)}");
Console.WriteLine($"Area 2 multiplier: {restored.Areas[2]}");
Console.WriteLine($"Same bytes: {state.SequenceEqual(restored.SaveState())}");

// Simulate an incomplete save by dropping the last byte.
try
{
    restored.RestoreState(state.AsSpan(0, state.Length - 1));
    throw new InvalidOperationException("Accepted a truncated snapshot.");
}
catch (GridStateException error)
{
    Console.WriteLine($"Rejected: {error.GetType().Name}");
}
Console.WriteLine($"Grid unchanged: {state.SequenceEqual(restored.SaveState())}");
```

`dotnet run` prints:

```text
Dimensions: 3 x 2
Cell (1,0): area 2
Cell (1,1): area 255
Area 2 multiplier: 5
Same bytes: True
Rejected: GridStateException
Grid unchanged: True
```

Area `255` means a wall (`AreaCosts.Wall`). If the data is truncated, `RestoreState` throws `GridStateException` and leaves the existing `Grid` unchanged.

## Variations

**Restore into the original grid.** Append this to the snippet at the top to undo a wall edit. The original cell is area 2 again.

```csharp
map.SetArea(1, 0, AreaCosts.Wall);
map.RestoreState(state);
Console.WriteLine(map.GetArea(1, 0));
```

```text
2
```

## Related recipes

- [Grid paths for wide units in C#](https://recursiveai.org/onepath/cookbook/pathfind-with-agent-clearance/)
- [Resume a search across ticks](https://recursiveai.org/onepath/cookbook/resume-path-search-across-ticks/)
- [Save and restore a navigation mesh](https://recursiveai.org/onepath/cookbook/snapshot-and-restore-navmesh-state/)

## The short answer

Call `Grid.SaveState()` to get a binary snapshot, then pass it to `Grid.FromState(bytes)` to create a new grid. If you need to keep the same object, use `grid.RestoreState(bytes)` instead; that grid must already have the saved width and height. This is a snapshot of the map, not an unfinished path query.

## What does a serialized pathfinding grid contain?

The [grid payload](https://github.com/recursive-ai-oss/onepath-csharp/blob/9da11631e6c0d85abbb302e51f0511b74fa728fd/docs/grids-state.md#L86-L89) includes its width, height, version, coordinate space, area table, and cells in row order. Keeping the area table matters: the byte `2` in the cell at `(1,0)` says which area the tile uses, but it doesn’t say that area 2 costs 5. The saved multiplier completes the definition. In the example, restoring and saving again produces the same bytes.

The byte array is the library’s binary format, not JSON and not the text map used to build the example. You can store those bytes as a binary file or in another store that preserves binary values. Clearance and cached indexes aren’t part of the payload; the grid derives them from the restored map.

## How do you restore a grid without losing the current map on a bad save?

Catch `GridStateException` when passing the stored bytes to `FromState` or `RestoreState`. The [restore contract](https://github.com/recursive-ai-oss/onepath-csharp/blob/9da11631e6c0d85abbb302e51f0511b74fa728fd/docs/grids-state.md#L24-L48) says that a `Grid` is unchanged when its restore throws that exception. The truncated snapshot in the example shows this for an in-place restore. That is format validation, not a promise that every possible change to the bytes will be detected. Don’t overlap a restore with queries or edits on the same grid.

A one-shot `FindPath` keeps no in-progress search to save. If your app uses a sliced search or replanner and must resume it rather than start it again, save that object’s state separately, restore the grid first, and restore the dependent object with the matching options. The snapshot can’t serialize delegate callbacks; your app supplies those again.
