Search code examples
c#uwpstoragefile

UWP Access Denied to StorageFile


I'm getting access denied when using

StorageFile.GetFileFromPathAsync(filePath)

From other posts and some documentation that I read UWP can only access to video lib, videos, (profile related folders) when declared in the Package.appxmanifest etc...

With FilePicker I have no problem accessing these locations, but the StorageFile.GetFileFromPathAsync was to automatically load those files into a list when the page loads.

How can I use this function to load files outside known folders video lib, videos, etc.


Solution

  • You can only use this method to access files on those safe paths UWP apps have access to. If you get access to another location via a file or folder picker, you must cache access to it using Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList. This API allows you to store an existing instance of StorageFile or StorageFolder and gives you a "token", which is a string by which you can later access the selected StorageItem again.

    StorageFile file = await savePicker.PickSaveFileAsync();
    if (file != null)
    {
        string faToken = StorageApplicationPermissions.FutureAccessList.Add(file);  
    }
    

    Now that the file is in FutureAccessList, you can later retrieve it:

    StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(faToken);
    

    Items stored in FutureAccessList survive even when the app is closed and reopened so it is probably the ideal solution for your use case. However, keep in mind the FutureAccessList can store at most 1000 items (see Docs), and you must maintain it - so if you no longer need an item, make sure you delete it, so that it does not count towards the limit anymore.

    The second solution would be to declare the broadFileSystemAccess capability. This is however a restricted capability and your app must have a good reason to use it.