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.
First, we need to define a place where we will keep our data.
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:
- Create a new file in our app’s local folder
- Create a stream from that file to write our object
- 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.
- Return “true” to indicate that everything worked.
Our loading method will:
- Open the file we saved our data to
- If that file doesn’t exist, we’ll return an empty or null object
- Create our DataContractSerializer for our data type
- Read the data and return the result
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.
5 Responses to Saving and Loading App Data (Windows Store C# UWP / 8.1)
Very good article. It helped me and saved my time.
I also was wondering if you could give some more info on how to call these methods
I greatly appreciate this. I could only ask for one more bit of detail. How to call these methods.
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?
Why you use FlushAsync() and Dispose() inside using block?
They will be automatically called.