Windows 7 Phone – Saving to Isolated Storage
I was recently asked how to save a serialised file to the Windows 7 phone isolated storage so I thought I’d post an example, similar to how I did this within my Windows 7 phone database Rapid Repository.
In this post, I’m going to show a simple example of:
- Creating a directory
- Building the file path
- Saving the file
To see how to load a file from isolated storage, see the following post http://weblogs.asp.net/seanmcalinden/archive/2010/11/18/windows-7-phone-loading-from-isolated-storage.aspx.
This post assumes that you have a serialised json file to save that is passed into the Save method along with a file name.
Here we go…
- public class SaveToIsolatedStorage
- {
- private string myDirectory = "MyDirectory";
- public void Save(string fileName, string jsonFile)
- {
- try
- {
- using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
- {
- fileName = String.Format("{0}.json", fileName);
- string filePath = Path.Combine(myDirectory, fileName);
- if (!store.DirectoryExists(myDirectory))
- {
- store.CreateDirectory(myDirectory);
- }
- using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, store))
- {
- using (StreamWriter stream = new StreamWriter(fileStream))
- {
- stream.Write(jsonFile);
- }
- }
- }
- }
- catch (IsolatedStorageException exception)
- {
- throw exception;
- }
- }
- }
As you can see, we get the user store for the application, this is then used for all our interaction with the isolated storage file system.
Once we have the store, a directory called MyDirectory is created if it doesn’t already exist.
Once we’re happy the directory exists we open a file stream and then use a stream writer to write the json file to isolated storage.
I hope that this is useful, if you would like to see a more ‘real world’ example – you can view the source of the Rapid Repository FileManager class here.
Kind Regards,
Sean McAlinden.