How to access files or folders the user picked in a previous session of my UWP app?

一笑奈何 提交于 2019-12-11 15:45:18

问题


My application asks the user to pick a single file (or an entire folder) from which I will load content. I can use the FileOpenPicker and FolderPicker classes for this, and it works fine. The problem is that if the user closes my app (or it gets suspended and terminated) I lose access to the StorageFile or StorageFolder that was returned from the picker. I don't want to ask the user to pick the same file or folder again (that would be annoying).

I have considered saving the Path of the file or folder into my settings and then using the broadFilesystemAccess capability to access the file or folder later on, but this is a Restricted capability that Microsoft has to approve. Is there a better way to re-open files or folders the user has previously opened in my app?


回答1:


The broadFilesystemAccess capability is not a good solution to this problem -- even putting aside the principle of least privilege that says you shouldn't ask for access to all the user's files when you only need access to one file, this is a capability that the user can turn off at any time, meaning you would lose access to the files / folders.

Instead, you should be using the FutureAccessList to store and then later retrieve any files or folders the user has given you access to. This class can also remember files saved via the FileSavePicker or opened via a File activation (eg, when the user double-clicks on a file in Windows Explorer) or via any other mechanism that provides you with a disk-backed IStorageItem.

You add the IStorageItem to the list and get back a 'token' that you can save in your app settings and then at any future point in time you can retrieve the item again with that token (assuming the file hasn't been moved, deleted, etc.)

// After user has picked file or folder, get the token and then
// store it in your local settings however you want.
var token = StorageApplicationPermissions.FutureAccessList.Add(file);
SaveLastFileUserWasWorkingOnToSettings(token);

// -----

// When your app is launched again, look up the last-opened file in 
// settings and then try to retrieve it.
var token = GetLastFileUserWasWorkingOnFromSettings();
if (StorageApplicationPermissions.FutureAccessList.ContainsItem(token))
{
  var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(token);
  // use the file...
}


来源:https://stackoverflow.com/questions/52227435/how-to-access-files-or-folders-the-user-picked-in-a-previous-session-of-my-uwp-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!