Have you ever had the need to read in an embedded content file when working in WinRT, how about using the PCL with WinRT? Maybe you have a .json or .xml file you want to use to test data (which is my case).
There are a ton of different suggestions on how to accomplish this on the net, I found most of them to partially accurate or just down right wrong. Because of this I thought I would demonstrate how I was able to accomplish this.
Step 1: Adding the file to be read to your project:
Below is my file to be read and its folder structure. You can see that my file is 2 folders off of the root.
Step 2: Setting the properties for this file:
Below is the screen shot of the properties panel (Right click the file and select properties). Pay attention to the fact that my Build Action is ‘Content’
Step 3: Create the logic to read in the file and return the contents as a string
Below is the code I used to read in the file.
public async static Task ReadJson()
var jsonFile = Path.Combine(Package.Current.InstalledLocation.Path, "JsonSerialization/json/DirectorySearchResults.json.txt");
var jsonFolder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(jsonFile));
using (var jsonStream = await jsonFolder.OpenStreamForReadAsync(Path.GetFileName(jsonFile)))
using (var streamReader = new StreamReader(jsonStream))
var json = streamReader.ReadToEnd();
When looking at the code above there I do need to call attention to the first line.
In the first line I am creating the path to my json file. When providing the name of the file make sure to provide the name of EACH folder in the file path. If you do not do this you will not like your results.
Hope this helps.
Till next time,
01-17-2014 9:07 AM