Remembering files from outside the application repository

A common scenario for file access in Windows 8 is to allow the user to pick a file from their hard drive, not necessarily from within one of the system-allowable locations such as the local data folder, pictures or documents library, etc. This is, of course, easily achievable using the FileOpenPicker control, but what happens if you want to persist that selection across runs of your app? If you just store a reference to the file location, subsequent runs won’t be granted access to the file and that could bring your app logic crashing down.

The answer is fairly simple. Use the FutureAccessList object in the StorageApplicationPermissions namespace. This allows you to store a file (or folder) along with a token in order to be able to use the IStorageItem later on.

This is a simple example page that uses the FutureAccessList to allow the user to set an image source, which is persisted across runs of the app. For the sake of clarity, I have removed XML comments from the code.

XAML

C#

So, what is happening here?

1) In OnNavigatedTo, the app will check to see if we have already set an image file. Let’s assume for now that we haven’t and skip forward.
2) When the user clicks the “Load Image” button, we show a filtered FileOpenPicker to pick a single file. Once we have the file back, we stash it in the FutureAccessList, along with a token to identify the file – in this case, just a string “pickedFileToken”.

3) I have moved the logic to render the file content to the “MyImageWithFileAccess” image out to a separate method. This opens a stream and sets the image source accordingly.
4) On the next run of the app (or visit to the page), we go back in to OnNavigatedTo. This method checks the FutureAccessList to see if we have set an image. In this case, we have, so it retrieves the StorageFile instance from the list and calls the SetImagePath method once more.

Notes:

  • There is no error handling here – if the user deletes the file, we will get an exception.
  • We are not removing items from the FutureAccessList if we no longer need them. This can be done by calling the Remove method on the list, passing in the token, or clearing the list entirely with the Clear() method.
  • The FutureAccessList can hold up to around 1000 items, but try to use it sparingly. If you are having to keep track of 1000 items, you may need to re-think your app logic.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">