Chuyển đến nội dung

Bài 27 · Data and Storage

Files and JSON in MAUI

Read and write files in a .NET MAUI app with FileSystem.AppDataDirectory, bundle read-only assets, and save objects as JSON with System.Text.Json, atomically and safely.

Preferences are fine for a handful of settings, but a to-do list, a shopping cart or a downloaded article needs a real file. Every MAUI app gets a private folder that other apps cannot read, and .NET gives you the same System.IO and System.Text.Json APIs you use on a server. This lesson shows where to put files, how to ship read-only data inside the app, and how to save objects without corrupting them.

MAUI's folder properties come from the platform, so the MAUI lines are shown read-only. The examples you can run use System.IO and System.Text.Json against a temporary folder, which behave the same on a phone.

Where files live

FileSystem exposes the folders your app may use:

Property Use it for Backed up?
FileSystem.AppDataDirectory Data the app creates and needs long-term: documents, databases Yes, on most platforms
FileSystem.CacheDirectory Temporary and re-creatable data, such as downloaded thumbnails No, the OS may delete it any time
C#
string dataFolder = FileSystem.AppDataDirectory;
string path = Path.Combine(dataFolder, "notes.json");

Always build paths with Path.Combine. Android uses /data/user/0/<app id>/files, iOS uses a sandbox path with a GUID, and Windows uses LocalState. The exact value changes between installs, so never store a full path. Store the file name and recombine it at runtime.

Reading and writing text

C#
string path = Path.Combine(FileSystem.AppDataDirectory, "hello.txt");

await File.WriteAllTextAsync(path, "Hello from MAUI");

if (File.Exists(path))
{
    string text = await File.ReadAllTextAsync(path);
}

File.Delete(path);

For larger files use streams (StreamReader, StreamWriter, FileStream) so you do not hold everything in memory. Always await file operations rather than blocking, because a blocked UI thread freezes the screen.

Files that ship with the app

Put read-only files (default data, a license text, an HTML page) into Resources/Raw. Their build action is MauiAsset and the default template already includes the folder. You cannot write to them. Read them as streams:

C#
using Stream stream = await FileSystem.OpenAppPackageFileAsync("seed-recipes.json");
using var reader = new StreamReader(stream);
string json = await reader.ReadToEndAsync();

A common pattern is to copy the asset to AppDataDirectory on first launch and from then on read and write the copy.

flowchart LR
    A["Resources/Raw/seed.json<br/>(read-only in the package)"] -- "first launch: copy" --> B["AppDataDirectory/data.json<br/>(read/write)"]
    B -- "app reads/writes" --> C["ViewModel"]

Seed data ships inside the app; the editable copy lives in the data folder.

JSON with System.Text.Json

Models are plain classes or records:

C#
public record TodoItem(int Id, string Title, bool Done, DateTime? DueDate);
C#
var options = new JsonSerializerOptions
{
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

string json = JsonSerializer.Serialize(items, options);
List<TodoItem>? back = JsonSerializer.Deserialize<List<TodoItem>>(json, options);

For faster start-up and for trimming and Native AOT (iOS releases are trimmed), use the source generator so no reflection is needed:

C#
[JsonSerializable(typeof(List<TodoItem>))]
[JsonSourceGenerationOptions(WriteIndented = true)]
internal partial class AppJsonContext : JsonSerializerContext { }

string json = JsonSerializer.Serialize(items, AppJsonContext.Default.ListTodoItem);

Without it, a release build with aggressive trimming can fail at runtime with a missing-member error, because the trimmer removed constructors it could not see being used.

Saving safely

If the app is killed halfway through writing, the file is half-written and unreadable. Write to a temporary file, then replace the original in one step:

C#
string temp = path + ".tmp";
await File.WriteAllTextAsync(temp, json);
File.Move(temp, path, overwrite: true);

Also guard reads: a missing file means "first launch", and a corrupt file should not crash the app. Return an empty list and, if you care, keep the broken file as *.bad for diagnostics.

Try it: a JSON repository with atomic saves

C# Stand-in: a JSON file repository

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In a MAUI app you would pass Path.Combine(FileSystem.AppDataDirectory, "todos.json") to the constructor. Nothing else changes, which is the point of keeping storage code free of MAUI types.

Try it: versioned data so old files keep working

Apps live for years. A file written by version 1 must still load in version 5. Store a version number and migrate on load.

C# Stand-in: JSON migration

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each migration upgrades one version, so a version-1 file moves through every step in order. This is the same idea database migrations use.

Other useful file tasks

  • Listing files: Directory.GetFiles(FileSystem.AppDataDirectory, "*.json").
  • Deleting old caches: loop over CacheDirectory and delete files older than a week.
  • Exporting to the user: write a file in the cache, then call Share.Default.RequestAsync(new ShareFileRequest(...)) (sharing).
  • Large downloads: stream the HTTP response straight to a FileStream instead of reading into a string (REST APIs).

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which folder may the operating system clear whenever it needs space?

    CacheDirectory is for temporary data that can be re-created; the OS may delete it.
  2. 2. Why write to a .tmp file and then File.Move over the original?

    The replacement is a single step, so you either have the old complete file or the new complete file.
  3. 3. Files in Resources/Raw are...

    They are packaged as MauiAsset and can only be read; copy them to AppDataDirectory to edit.
  4. 4. Why use a System.Text.Json source generator in a MAUI release build?

    Generated serializers do not depend on reflection, so they survive trimming and Native AOT.

Summary

  • Use AppDataDirectory for durable data and CacheDirectory for disposable data; never store absolute paths.
  • Ship read-only data in Resources/Raw and copy it if you need to edit it.
  • Serialize with System.Text.Json (source-generated for release builds) and save atomically.
  • Handle missing and corrupt files, and version your data so upgrades keep old files readable.

Next: SQLite Local Database

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.