Quantcast
Channel: WiredPrairie » Windows 8
Viewing all articles
Browse latest Browse all 4

Reading a text file (or JSON file) from a Windows 8 Runtime application

$
0
0

I just had need of reading a small JSON file into a Windows 8 application using the Windows Runtime.

Uri uri = new Uri("ms-appx:///assets/data.json");

var storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

using (var storageStream = await storageFile.OpenReadAsync())
{
using (Stream stream = storageStream.AsStreamForRead())
{
using (StreamReader reader = new StreamReader(stream))
{
var jsonText = reader.ReadToEnd();
var results = JsonConvert.DeserializeObject<DemoData>(jsonText);
this.DataContext = results;
}
}
}

What seemed like it should have been a common example on MSDN was not …, and after a bit of searching and reading, I believe the above code represents at least a common and safe way of loading data.

I’ve got a file called data.json stored in an Assets folder:

image

And the file’s Build Action is set to Content:

image

Change the value passed to the Uri constructor and … the file will be loaded successfully. Once loaded, I used the strongly typed generic DeserializeObject method to convert the Json data to a class called DemoData.


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images