You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:26:15