| MAUI-CommunityToolkit-7 :👈 | 👉:MAUI-CommunityToolkit-9 |
Hour 8 β Data Persistence (Preferences, SecureStorage, SQLite, File I/O) |
π Hour 8 β Data Persistence in .NET MAUI
Welcome to Hour 8 of your MAUI MVVM series. Today we cover how MAUI apps store and load data using:
- β‘ Preferences (key-value storage)
- β‘ SecureStorage (encrypted storage)
- β‘ SQLite Database
- β‘ File I/O (local files)
β¨ 1. Preferences (Simple KeyβValue Storage)
Preferences are used to save small data such as settings, flags, or strings.
π₯ 1.1 Saving Data
Preferences.Set("username", "john");
Preferences.Set("isLoggedIn", true);
π€ 1.2 Retrieving Data
string user = Preferences.Get("username", "Guest");
bool logged = Preferences.Get("isLoggedIn", false);
π 1.3 Removing Data
Preferences.Remove("username");
Preferences.Clear();
β Use Preferences for nonβsensitive settings.
β¨ 2. SecureStorage (Encrypted Storage)
SecureStorage encrypts data using device-level protection. Use it for API tokens, passwords, and sensitive user info.
π 2.1 Saving Secure Data
await SecureStorage.SetAsync("token", "ABC123");
π 2.2 Retrieving Secure Data
string token = await SecureStorage.GetAsync("token");
β Automatically encrypted β Keychain (iOS/macOS), Keystore (Android)
β¨ 3. SQLite Database
SQLite is the best option for structured or relational data storage. MAUI uses SQLite-net library.
π¦ 3.1 Install Package
dotnet add package sqlite-net-pcl
π 3.2 Create a Model
public class Note
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Text { get; set; }
public DateTime Created { get; set; }
}
π 3.3 Create Database Service
public class NotesDatabase
{
private readonly SQLiteAsyncConnection db;
public NotesDatabase(string path)
{
db = new SQLiteAsyncConnection(path);
db.CreateTableAsync<Note>().Wait();
}
public Task<List<Note>> GetNotesAsync()
{
return db.Table<Note>().ToListAsync();
}
public Task SaveNoteAsync(Note note)
{
return db.InsertAsync(note);
}
}
π§ 3.4 Register DB in MauiProgram
string dbPath = Path.Combine(FileSystem.AppDataDirectory, "notes.db3");
builder.Services.AddSingleton(new NotesDatabase(dbPath));
β‘ 3.5 Use in ViewModel
public partial class NotesViewModel : ObservableObject
{
private readonly NotesDatabase db;
public NotesViewModel(NotesDatabase service)
{
db = service;
}
[ObservableProperty]
private List<Note> notes;
[RelayCommand]
private async Task LoadNotes()
{
Notes = await db.GetNotesAsync();
}
}
β SQLite is ideal for offline apps.
β¨ 4. File I/O (Read/Write Local Files)
MAUI gives access to device folders like AppDataDirectory.
π 4.1 Saving a File
string path = Path.Combine(FileSystem.AppDataDirectory, "data.txt");
File.WriteAllText(path, "Hello world");
π 4.2 Reading a File
string content = File.ReadAllText(path);
π 4.3 Using Async File Helpers
await File.WriteAllTextAsync(path, "Async content");
string text = await File.ReadAllTextAsync(path);
β Good for logs, exports, user-generated text.
β¨ 5. Full Example β Save Data in All Methods
public partial class SettingsViewModel : ObservableObject
{
[ObservableProperty]
private string username;
[ObservableProperty]
private string secureToken;
[ObservableProperty]
private string fileContent;
private readonly NotesDatabase db;
public SettingsViewModel(NotesDatabase database)
{
db = database;
}
[RelayCommand]
private void SavePreferences()
{
Preferences.Set("username", Username);
}
[RelayCommand]
private async Task SaveSecure()
{
await SecureStorage.SetAsync("token", SecureToken);
}
[RelayCommand]
private async Task SaveFile()
{
string path = Path.Combine(FileSystem.AppDataDirectory, "data.txt");
await File.WriteAllTextAsync(path, FileContent);
}
[RelayCommand]
private async Task SaveNote()
{
await db.SaveNoteAsync(new Note
{
Text = FileContent,
Created = DateTime.Now
});
}
}
π Hour 8 Summary
- β Preferences β simple key-value settings
- β SecureStorage β encrypted sensitive data
- β SQLite β relational local database
- β File I/O β reading/writing text files
- β MAUI provides multiple storage options for real apps
| MAUI-CommunityToolkit-7 :👈 | 👉:MAUI-CommunityToolkit-9 |