Storage Options

.NET MAUI provides multiple storage options for caching data locally on a device, depending on the nature, structure, and size of the data.

The three most commonly used options for storing data locally in a .NET MAUI app are:

  • Preferences: Stores data in key-value pairs

  • File system: Stores loose files directly on the device through file system access

  • Database: Stores data in a relational database

Preferences

Stores data in key-value pairs

  • Preferences are convenient when you're working with simple pieces of data, such as user selections.

  • They're often used to enable users to configure the application.

For example, suppose you wanted the user to be able to specify whether the app should save their username and password between session. You can store the user's choice in Preferences.

File system

Stores loose files directly on the device through file system access

  • It's convenient to use the file system when you have loose files such as XML, binary, or text files.

For example, suppose you want to store log data locally on the device. You can create a text file, save this file to the file system, and write logs to it as events happen. You can also serialize large data structures to a file, and cache it locally on the file system if you need to save when the app shuts down. When the app restarts, you can re-read this data back into memory.

Database

Stores data in a relational database

  • It's a good idea to use a local database when you have relationships between data, or when you want to filter the data over time.

For example, in the social media example, each post contains data about the post, such as the timestamp and the contents. However, each post also has a relationship to a user who made the post. It makes sense to represent this relationship in a database to prevent data duplication between posts, and also to improve the efficiency of searching for data.

A SQLite database is a file, and you need to store it in an appropriate place. Ideally, you should create a folder under the AppDataDirectory folder in the sandbox and create the database in this folder.

Last updated