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
Back to Index
MAUI-CommunityToolkit-7 :👈 👉:MAUI-CommunityToolkit-9
*