如何在UWP应用中获取通过FileOpenPicker打开文件的路径?
UWP中获取FileOpenPicker选中文件的路径
核心方法:使用StorageFile.Path属性
在你获取到StorageFile实例后,直接访问它的Path属性就能得到文件的完整系统路径。修改你的代码如下:
FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.Desktop; openPicker.FileTypeFilter.Add(".txt"); StorageFile storageFile = await openPicker.PickSingleFileAsync(); if (storageFile != null) { // 获取文件路径 string filePath = storageFile.Path; // 你的原有文件读取逻辑 var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite); using (StreamReader sReader = new StreamReader(stream.AsStream())) { Document.Text = sReader.ReadToEnd(); Document.IsSaved = true; } }
关键注意事项
- UWP基于沙盒机制运行,即使拿到文件路径,也不能直接用传统的
System.IO.File类(如File.Open)操作文件,否则会触发权限异常,必须通过StorageFile提供的API(如OpenAsync)处理文件。 - 对于OneDrive、OneDrive for Business等云存储中的文件,
Path属性可能返回空或虚拟路径,此时完全依赖StorageFile的API进行操作是唯一可靠的方式。 - 如果需要持久化访问该文件(比如下次启动应用时直接打开),不要保存文件路径,而是将
StorageFile添加到FutureAccessList中保存访问令牌:
if (storageFile != null) { // 将文件添加到未来访问列表,获取唯一令牌 string accessToken = StorageApplicationPermissions.FutureAccessList.Add(storageFile); // 保存accessToken到本地(比如用ApplicationData.Current.LocalSettings) // 后续需要访问时,通过令牌获取文件 // StorageFile savedFile = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(accessToken); string filePath = storageFile.Path; // 原有逻辑... }
内容的提问来源于stack exchange,提问作者Alper Akca
相关产品推荐
相关产品推荐

