Skip to content

Saving and Loading App Data (Windows Store C# UWP / 8.1)

Every application needs to save information, usually in the form of objects or lists of objects.

To ease Windows (Phone) app development, I have my data saving process templated in a Visual Studio snippet. It’s an incredibly useful way for me to build out the basics quickly, especially for prototyping.

Download Snippet

First, we need to define a place where we will keep our data.

image

Note: If you want your data to live on multiple devices, make sure you replace “LocalFolder” with “RoamingFolder”. If you keep your data small (100KB limit) your data will be transfered across all devices the user has your app installed on.

Our loading and saving methods will operate statically so we don’t need to initialize an object to get our data. In the saving  method, we will:

  1. Create a new file in our app’s local folder
  2. Create a stream from that file to write our object
  3. Use DataContractSerializer of our data type to write our data. I’m using this b/c it’s built into the Windows platform. I actually prefer JSON.NET for this task.
  4. Return “true” to indicate that everything worked.image

Our loading method will:

  1. Open the file we saved our data to
  2. If that file doesn’t exist, we’ll return an empty or null object
  3. Create our DataContractSerializer for our data type
  4. Read the data and return the result

image

Obviously, this can be abstracted to be more useful in a variety of scenarios. But if you do a lot of rapid prototyping, this is a great way to bootstrap some basic data saving / loading.