In my most recent posting on Conference Buddy, I showed how to store the data we’ll be accumulating in JSON format. Today, I’ll show how to write that JSON data to a file for local storage.
Let’s return to the application; if you need a starting point you can download the source here.
Windows Store applications cannot just access any file anywhere on the local machine. They must access files only in certain known locations. You set access permission using the capabilities tab of the appx manifest; in this case checking the Documents Library to allow writing to the Documents folder.
When you set this, however, you’ll discover that you need to provide additional file-association settings. Even applications that have access to the Documents Library must specify the supported extensions in advance. This is done through the Declarations tab.
First, in the Available Declarations drop down, select File Type Associations and click Add. Under Properties select a Display name and a Name and check Open is Safe. In the Supported Files Type section add a content type (text/plain) and a File type (.json). Feel free to make up your own extension, as I have done here.
Creating the View Model
We will need a ViewModel to act as the DataContext for our View. Create a new file named MainViewModel and have it implement INotifyPropertyChanged (you’ll need to add a using statement for System.ComponentModel).
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged( string p )
{
if ( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( p ) );
}
Add a property for the current folder, which will be of type StorageFolder. Storage folders are used to manipulate both folders and their contents. You can read more about StorageFolders here.
private StorageFolder _currentFolder;
public StorageFolder CurrentFolder
{
get { return _currentFolder; }
set
{
_currentFolder = value;
NotifyPropertyChanged( "CurrentFolder" );
}
}
We can now add a method to set the CurrentFolder to the DocumentsLibrary using the KnownFolders object. The KnownFolders static class provides access to common locations that contain user content, such as in libraries HomeGroup, etc. You can learn more about the KnownFolder class here.
public void LoadDocumentsLibrary()
{
CurrentFolder = KnownFolders.DocumentsLibrary;
}
We are now ready to create the key method in our ViewModel: CreateFile. This method will take a sub-folder name and a file name and will create or open each in turn, returning a StorageFile. Because the method to create the folder is Asynchronous (as is the method to open a file) we’ll use the await keyword, and thus will mark this method with the async keyword and will return a Task<StorageFile>,
public async Task<StorageFile> CreateFile( string subFolderName, string fileName )
{
if ( CurrentFolder != null )
{
var folder = await CurrentFolder.CreateFolderAsync(
subFolderName, CreationCollisionOption.OpenIfExists );
return await folder.CreateFileAsync(
fileName, CreationCollisionOption.OpenIfExists ).AsTask();
}
else
return null;
}

private void Save_Click( object sender, RoutedEventArgs e )
{
Customer cust = new Customer();
cust.Company = Company.Text;
cust.Email = Email.Text;
cust.FirstName = FirstName.Text;
cust.LastName = LastName.Text;
cust.PhoneNumber = PhoneNumber.Text;
cust.Title = Title.Text;
string JSON = JsonConvert.SerializeObject( cust );
Message.Text = JSON;
WriteToFile( JSON );
ClearFields();
}
Notice the new call to WriteToFile, passing in the JSON string. The Helper method WriteToFile starts by obtaining the names of the subdirectory and the file we’ll be writing to. These could well be in the application’s settings; for now we’ll just hardwire them,
private async void WriteToFile(string json)
{
string folderName = "ConferenceBuddy";
string fileName = "ConferenceBuddy.json";
Next, we’ll set the local variable contents to the json string that was passed in, and we’ll se the current directory to the Documents directory,
string contents = json;
_vm.LoadDocumentsLibrary();
We are ready to write the file, which we do by calling CreateFile on the VM,
var file = await _vm.CreateFile( folderName, fileName );
We get back an object of type Windows.Storage.StorageFile which we can check to ensure is not null and if not, we can use to write the contents to the file,
if ( file != null )
{
await FileIO.AppendTextAsync( file, contents );
}
If it is null, we’ll display a modal message dialog indicating that we were unable to create the file,
else
{
var dlg = new MessageDialog( "Unable to create file" );
await dlg.ShowAsync();
}
The file will be opened, appended to and closed. Here is the JSON that’s written to the file:
{“Email”:“[email protected]”,“FirstName”:“Jesse”,“LastName”:“Liberty”,“Title”:“XAML Evangelist”,“Company”:“Telerik”,“PhoneNumber”:“617-848-9684”}
{“Email”:“[email protected]”,“FirstName”:“Michael”,“LastName”:“Crump”,“Title”:“XAML Evangelist”,“Company”:“Telerik”,“PhoneNumber”:“Unknown”}
{“Email”:“[email protected]”,“FirstName”:“Stacey”,“LastName”:“Liberty”,“Title”:“QA Specialist”,“Company”:“Liberty Associates, Inc.”,“PhoneNumber”:“617-848-9684”}
Download the Source Code Here.
In this blog post we saw how to add the data to a file. In a future post we’ll look at how we might store this data to the cloud.
I truly appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You’ve made my day! Thank you again!
I’m truly enjoying the design and layout of your website. It’s a very easy on the eyes
which makes it much more pleasant for me to come here and
visit more often. Did you hire out a developer to create your
theme? Excellent work!
My weblog: Stacey
Hi Jesse,
I’ve been reading your articles for a while now and I must say I enjoy every time! Excellent work you are doing here, thank you!
Q: Have you tried (considered) this with OData stream and Entity Framework 5? If so, would you care please to share your findings (recommendations) briefly?