Windows Phone 8 HowTo with C#: reading a local file’s content from code
Posted: (EET/GMT+2)
In Windows Phone 8 (Universal applications) programming you might have a very simple need: you have a file in your Visual Studio project that you would like to read at runtime from code. Turns out that finding a solution for this isn't trivial (via Google, Bing or otherwise), so I wanted to blog about it.
To work with local files in the project, add the file (say, a HTML file) to your project, and set the file's Build Action to Content. Then, use the following code to read it:
string html = await Windows.Storage.PathIO.ReadTextAsync("ms-appx:///MyFile.html");
When the file "MyFile.html" is at the root of your project, you can read it using the above code. Likewise, if you have the file in a sub-folder, then simply add the path to the above "ms-appx" URL:
ms-appx:///SomeSubfolder/MyFile.html
With the above code, you can get the contents of a text-based file. In case you wanted to display this particular HTML code in the embedded web browser component (the WebView class), you can display the above-loaded HTML string like this:
webView1.NavigateToString(html);
This works pretty well for simple about pages, help files, etc. that must work offline, too.
Hope this helps!