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

UWP调用StorageFolder.GetFolderFromPathAsync时抛出E_ACCESSDENIED异常

解决UWP中StorageFolder.GetFolderFromPathAsync访问路径时的权限拒绝问题

问题根源

UWP应用基于沙箱机制运行,默认仅能访问应用自身沙箱目录、系统已知库(如图片/视频库,需声明权限),或用户手动选择授权的文件夹。直接通过绝对路径调用StorageFolder.GetFolderFromPathAsync访问非授权路径,必然触发E_ACCESSDENIED错误。

解决方案

方案1:使用文件选择器让用户手动授权(推荐,符合UWP权限设计)

让用户通过FolderPicker选择目标文件夹,应用对用户手动选择的文件夹拥有访问权限,无需额外权限声明(仅需确保应用有基本文件访问能力)。

修改SetupUiAsync方法如下:

private async Task SetupUiAsync()
{
    var folderPicker = new FolderPicker();
    folderPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    folderPicker.FileTypeFilter.Add("*"); // 允许选择任意类型文件夹

    var lvmptVid = await folderPicker.PickSingleFolderAsync();
    if (lvmptVid != null)
    {
        // 保留对该文件夹的访问权限,重启应用后仍可访问
        StorageApplicationPermissions.FutureAccessList.AddOrReplace("CapturesFolder", lvmptVid);
        _captureFolder = lvmptVid;
    }
    else
    {
        // 用户取消选择,降级到应用本地存储
        var localFolder = ApplicationData.Current.LocalFolder;
        _captureFolder = localFolder;
    }
}

方案2:声明Documents Library权限(仅适用于访问Documents目录下路径)

如果目标文件夹在Documents目录下,可通过声明权限实现访问:

  1. 打开Package.appxmanifest文件,切换到功能标签页,勾选文档库。
  2. 切换到代码视图,在<Capabilities>节点下添加文件类型关联(UWP要求访问库必须指定允许的文件类型):
<Capabilities>
    <Capability Name="internetClient" />
    <Capability Name="documentsLibrary" />
    <!-- 添加文件类型关联 -->
    <Extensions>
        <uap:Extension Category="windows.fileTypeAssociation">
            <uap:FileTypeAssociation Name="video">
                <uap:SupportedFileTypes>
                    <uap:FileType>.mp4</uap:FileType>
                </uap:SupportedFileTypes>
            </uap:FileTypeAssociation>
        </uap:Extension>
    </Extensions>
</Capabilities>
  1. 此时可直接访问Documents目录下的子文件夹:
private async Task SetupUiAsync()
{
    // 获取Documents库根目录
    var documentsLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Documents);
    // 获取或创建目标子文件夹
    var lvmptVid = await documentsLibrary.SaveFolder.CreateFolderAsync("lvmptVid", CreationCollisionOption.OpenIfExists);
    _captureFolder = lvmptVid;
}

方案3:使用BroadFileSystemAccess权限(不推荐,仅特殊场景使用)

该权限允许应用访问任意本地文件,但属于受限权限,提交应用商店时需说明用途,且用户需手动开启:

  1. 在Package.appxmanifest代码视图中添加:
<Capabilities>
    <rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>
  1. 用户需前往设置>隐私和安全性>文件系统,找到你的应用并开启权限。

注意:此权限仅适用于桌面版UWP应用,不符合UWP安全设计理念,仅必要时使用。

内容的提问来源于stack exchange,提问作者Michael A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:02:10