能否将指定StorageFolder设为FolderPicker初始文件夹?
关于UWP FolderPicker设置自定义初始文件夹的问题
首先直接给结论:通过SuggestedStartLocation直接设置从FutureAccessList获取的StorageFolder是不可行的,但有专门的API可以实现你的需求,下面详细说明:
为什么直接用SuggestedStartLocation不行?
SuggestedStartLocation的类型是PickerLocationId,这是一个系统预设的枚举,只能指定像PickerLocationId.DocumentsLibrary、PickerLocationId.PicturesLibrary这类系统内置的位置,没法直接关联你通过FutureAccessList拿到的自定义文件夹——毕竟枚举值里不可能包含用户任意选择的文件夹路径。
可行的解决方案
方案1:Windows 10 1809(Build 17763)及以上版本(推荐)
微软在这个版本之后给FolderPicker添加了TrySetCurrentFolderAsync()方法,允许直接传入一个已授权的StorageFolder作为初始位置。刚好你从FutureAccessList获取的文件夹已经是用户授权过的,完全符合使用条件。
示例代码:
// 从FutureAccessList获取目标文件夹 StorageFolder aFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(encodeFolderString); // 初始化FolderPicker var folderPicker = new FolderPicker(); // 注意:必须设置FileTypeFilter,否则Picker无法正常启动 folderPicker.FileTypeFilter.Add("*"); // 判断系统版本是否支持该方法 if (ApiInformation.IsMethodPresent("Windows.Storage.Pickers.FolderPicker", "TrySetCurrentFolderAsync")) { // 尝试设置初始文件夹 bool isSetSuccess = await folderPicker.TrySetCurrentFolderAsync(aFolder); // 可选:根据isSetSuccess的值处理设置失败的情况(比如文件夹已被删除) } // 显示Picker StorageFolder selectedFolder = await folderPicker.PickSingleFolderAsync();
方案2:针对旧版本Windows 10(低于1809)
如果你需要兼容更早的系统,可以使用SettingsIdentifier属性:给不同的Picker场景设置唯一的标识符,Picker会记住用户上次在该场景下选择的文件夹。如果你的aFolder是用户之前通过Picker选择过的,那么设置相同的SettingsIdentifier后,Picker会自动定位到该文件夹。
示例代码:
var folderPicker = new FolderPicker(); folderPicker.FileTypeFilter.Add("*"); // 设置唯一的场景标识符 folderPicker.SettingsIdentifier = "MyCustomFolderPicker"; // 显示Picker,下次启动时会默认打开用户上次选择的文件夹 StorageFolder selectedFolder = await folderPicker.PickSingleFolderAsync();
不过这个方案的局限性很明显:它依赖用户的选择历史,无法强制指定到你想要的aFolder,只能作为备选。
关键注意点
- 无论哪种方案,必须设置
FileTypeFilter,哪怕你只是要选择文件夹,也需要添加至少一个过滤项(比如"*"),否则FolderPicker会无法正常显示。 TrySetCurrentFolderAsync()返回的bool值可以用来判断设置是否成功,比如当目标文件夹已被用户删除或移动时,会返回false,这时可以 fallback 到SuggestedStartLocation。
内容的提问来源于stack exchange,提问作者arachide
相关产品推荐
相关产品推荐

