Accessing Bundled Content in UWP Applications
The way you access files on disk in UWP applications is through the StorageFile API. This allows you to read files but only from folders you have the rights to read from, which is pretty locked down in UWP. This is of course a good thing, but what if you want to ship a static data file with your application and access it as a StorageFile
from inside the application.
It took me a while to work out how you can do this, so I thought I’d share the solution I found.
First of all, add your bundled data file into your project, for example in the Assets
folder. Here, I’ve added in an MP3 file:
Now, make sure that the build action is set to Content
. The Copy to Output Directory flag does not need to be set to copy.
Now, when we want to access this as a stored file, we use the StorageFile.GetFileFromApplicationUriAsync
method and pass in a specially formatted Uri with the ms-appx://
protocol, like this:
var storageFile = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Assets/GuitarTest1.mp3"));
And that’s all there is to it. The StorageFile
you get is of course read-only, but it can be passed to any API that expects a StorageFile
.
Hope someone else finds this helpful, and do let me know in the comments if there is a better way to ship bundled content with your UWP applications.
Comments
great article --- just what I needed
Jeffrey BerezinHelpful!
Hitek Lonoshcin