Overview
.NET Multi-platform App UI (MAUI) provides several APIs to store data locally on the device. Choose the API that best matches your scenario:
File System
The FileSystem
API gives you access to the app's Documents and Cache directories. Use it for larger data such as JSON files, images, or PDFs.
// Write a text file to the Documents folder
string fileName = "notes.txt";
string content = "Hello MAUI Storage!";
string filePath = Path.Combine(FileSystem.AppDataDirectory, fileName);
File.WriteAllText(filePath, content);
// Read the file back
if (File.Exists(filePath))
{
string read = File.ReadAllText(filePath);
Console.WriteLine(read);
}
To work with binary data, use FileStream
or File.WriteAllBytes
:
// Save an image to the cache folder
byte[] imageBytes = await File.ReadAllBytesAsync("Resources/Images/logo.png");
string cachePath = Path.Combine(FileSystem.CacheDirectory, "logo.png");
await File.WriteAllBytesAsync(cachePath, imageBytes);
Preferences
When you need to store small amounts of primitive data (bool, int, string, double), Preferences
is the simplest solution. Preferences are automatically persisted across app restarts.
// Save a value
Preferences.Default.Set("username", "john.doe");
// Retrieve a value with a default fallback
string user = Preferences.Default.Get("username", "unknown");
Console.WriteLine($"Current user: {user}");
// Remove a specific key
Preferences.Default.Remove("username");
// Clear all preferences (use with caution)
Preferences.Default.Clear();
Preferences are stored per platform (UserDefaults on iOS, SharedPreferences on Android, etc.) and are not encrypted.
Secure Storage
For sensitive data such as tokens or passwords, use SecureStorage
. The data is encrypted using the platform's keystore (Keychain on iOS, Android Keystore, Windows Credential Locker).
// Store a secret
await SecureStorage.Default.SetAsync("auth_token", "eyJhbGciOiJI...");
// Retrieve the secret
try
{
string token = await SecureStorage.Default.GetAsync("auth_token");
Console.WriteLine($"Token: {token}");
}
catch (Exception ex)
{
// Possible that the device doesn't have secure storage or user denied access
Console.WriteLine($"Secure storage error: {ex.Message}");
}
SecureStorage may throw an exception if the device doesn't support it or the user revokes permission. Always handle exceptions gracefully.
Summary
Choose the right storage mechanism for your scenario:
Scenario | API |
---|---|
Large files, images, documents | FileSystem |
User settings, flags, small strings | Preferences |
Tokens, passwords, secrets | SecureStorage |
For more advanced scenarios, such as relational data, consider using SQLite or Azure Mobile Apps.