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

如何在未打包的Windows SDK应用中访问Assets文件夹?

UWP中访问Assets文件夹的问题解决

问题背景

我在csproj文件中添加了以下代码,确保安装后能访问Assets文件夹:

<ItemGroup> 
  <None Update="Assets/*">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory> 
  </None> 
</ItemGroup>

但找不到相关访问文档,尝试使用相关代码时,string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;这行抛出了InvalidOperationException异常。

原因分析

直接访问InstalledLocation.Path会触发异常,因为UWP应用的安装目录是受系统保护的,不能通过文件路径直接访问,必须使用UWP专属的StorageFolder/StorageFile异步API来操作,不能用传统的System.IO类方法。

正确访问Assets文件夹的方法

方法1:通过InstalledLocation获取Assets文件夹

使用异步API直接获取Assets文件夹,无需操作路径字符串:

// 获取应用安装目录下的Assets文件夹
StorageFolder assetsFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");

// 读取文件夹内的目标文件,例如example.txt
StorageFile targetFile = await assetsFolder.GetFileAsync("example.txt");
string fileContent = await FileIO.ReadTextAsync(targetFile);

方法2:使用ms-appx:///协议直接定位文件

也可以通过UWP专属的URI协议直接定位Assets里的文件:

Uri fileUri = new Uri("ms-appx:///Assets/example.txt");
StorageFile targetFile = await StorageFile.GetFileFromApplicationUriAsync(fileUri);
string fileContent = await FileIO.ReadTextAsync(targetFile);

补充说明

  • 你在csproj中配置的<CopyToOutputDirectory>Always</CopyToOutputDirectory>是正确的,它能确保Assets目录下的文件被复制到应用安装目录中。
  • 绝对不要用System.IO.File等传统IO类访问UWP应用的安装目录,这类操作会因权限限制直接失败。

内容的提问来源于stack exchange,提问作者John Glen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:40:24