如何访问用户在我的UWP应用的上一个会话中选择的文件或文件夹?

时间:2018-09-07 17:51:34

标签: uwp

我的应用程序要求用户选择一个我将从中加载内容的文件(或整个文件夹)。我可以为此使用FileOpenPickerFolderPicker类,它可以正常工作。问题是,如果用户关闭我的应用程序(或者它被挂起并终止),我将无法访问从选择器返回的StorageFileStorageFolder。我不想让用户再次选择相同的文件或文件夹(这很烦人)。

我考虑过将文件或文件夹的Path保存到我的设置中,然后在以后使用broadFilesystemAccess功能访问文件或文件夹,但这是Microsoft必须具有的受限功能批准。有没有更好的方法可以重新打开用户以前在我的应用程序中打开过的文件或文件夹?

1 个答案:

答案 0 :(得分:4)

broadFilesystemAccess功能对这个问题不是一个很好的解决方案-甚至将principle of least privilege放在一边,说您不应该要求访问所有 用户的文件,而您只需要访问一个文件,这是用户可以随时关闭的功能,这意味着您将失去对文件/文件夹的访问权限。

相反,您应该使用FutureAccessList进行存储,然后再检索用户已授予您访问权限的任何文件或文件夹。此类还可以记住通过FileSavePicker保存的文件或通过File激活打开的文件(例如,当用户双击Windows资源管理器中的文件时)或通过其他任何可以为您提供帮助的机制磁盘备份的IStorageItem

您将IStorageItem添加到列表中,并取回可以保存在应用程序设置中的“令牌”,然后在以后的任何时间点都可以使用该令牌再次检索该项目(假设文件还没有被移动,删除等)

// 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...
}