Matthias Shapiro

I need fewer hobbies

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.

This entry was posted in c#, UWP, Windows Phone, Windows Store. Bookmark the permalink.

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

  1. Archana

    Very good article. It helped me and saved my time.

  2. Matthew

    I also was wondering if you could give some more info on how to call these methods

  3. Rich

    I greatly appreciate this. I could only ask for one more bit of detail. How to call these methods.

    • matthiasshapiro

      I’m not sure what you mean. What kinds of details would you like around these methods? Things like file saving options? File name details?

  4. Ennio Morrikone

    Why you use FlushAsync() and Dispose() inside using block?
    They will be automatically called.