When working with a C#/XAML WinRT application it is common that you will include resources such as images, files, audio recordings, etc inside your deployment package. It will also be common that you may want to access these resources as native storage files in order to do things like share them between applications. Accessing these files is actually pretty easy and is only about 3 lines of code.
Before we get started assume that we have a directory structure inside our application as follows
root/Images/Image1.png
root/Images/Image2.png
root/Images/Image3.png
root/Images/Image4.png
When accessing our local files we will first want get the StorageFolder of the InstalledLocation of our package. This can be done as follows
var packageLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
Now that we have the StorageFolder (packageLocation) we want we can get the “Images” folder as follows
var imagesFolder = await packageLocation.GetFolderAsync("Images");
Once we have our images folder it is simple as asking for the given file as follows
var image = await imagesFolder.GetFileAsync(“Image1.png”);
Now that we have our Image we also have our IStorageFile. This allows us to pass this file to another application via the Share Contract, or to create a stream reference out of via the RandomAccessStreamReference.CreateFromFile(image) method.
Here is all the code in one block
var packageLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
var imagesFolder = await packageLocation.GetFolderAsync("Images");
var image = await imagesFolder.GetFileAsync(“Image1.png”);
// if you want the file as a stream (say to put into a Bitmap control
var imageStreamRef = RandomAccessStreamReference.CreateFromFile(image);
As you can see from above, this is pretty easy as well as pretty powerful.
Till next time
Posted
06-26-2012 8:52 AM
by
Derik Whittaker