UWP 无法通过 FolderPicker 从硬盘访问文件夹

UWP cannot get access to folder from hard drive via FolderPicker

我想使用 UWP 应用程序读取本地硬盘中某个文件夹(包括子文件夹)中的所有图像文件。

我从 FolderPicker 开始,以便用户可以选择想要的文件夹:

public async static Task<string> GetFolderPathFromTheUser()
    {
        FolderPicker folderPicker = new FolderPicker();
        folderPicker.ViewMode = PickerViewMode.Thumbnail;
        folderPicker.FileTypeFilter.Add(".");
        var folder = await folderPicker.PickSingleFolderAsync();
        return folder.Path;
    }

成功获取文件夹路径后,我正在尝试访问该文件夹:

 public async static Task<bool> IsContainImageFiles(string path)
    {
        StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);
        IReadOnlyList<StorageFile> temp= await folder.GetFilesAsync();
        foreach (StorageFile sf in temp)   
        {
            if (sf.ContentType == "jpg")
                return true;
        }
        return false;
    }

然后我得到下一个异常:

An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll but was not handled in user code WinRT information: Cannot access the specified file or folder (D:\test). The item is not in a location that the application has access to (including application data folders, folders that are accessible via capabilities, and persisted items in the StorageApplicationPermissions lists). Verify that the file is not marked with system or hidden file attributes.

那么我怎样才能获得从文件夹中读取文件的权限呢?

谢谢。

从文件选择器中获取文件夹后,您可能无法通过其路径访问该文件夹。您需要直接使用返回的 StorageFolder 实例:

public async static Task<IStorageFolder> GetFolderPathFromTheUser()
{
    FolderPicker folderPicker = new FolderPicker();
    folderPicker.ViewMode = PickerViewMode.Thumbnail;
    folderPicker.FileTypeFilter.Add(".");
    var folder = await folderPicker.PickSingleFolderAsync();
    return folder;
}

public async static Task<bool> IsContainImageFiles(IStorageFolder folder)
{
    IReadOnlyList<StorageFile> temp= await folder.GetFilesAsync();
    foreach (StorageFile sf in temp)   
    {
        if (sf.ContentType == "jpg")
            return true;
    }
    return false;
}

如果以后要访问它,应该将它添加到future access list并保留返回的令牌:

public async static Task<string> GetFolderPathFromTheUser()
{
    FolderPicker folderPicker = new FolderPicker();
    folderPicker.ViewMode = PickerViewMode.Thumbnail;
    folderPicker.FileTypeFilter.Add(".");
    var folder = await folderPicker.PickSingleFolderAsync();
    return FutureAccessList.Add(folder); 
}
public async static Task<bool> IsContainImageFiles(string accessToken)
{
    IStorageFolder folder = await FutureAccessList.GetFolderAsync(accessToken);
    IReadOnlyList<StorageFile> temp= await folder.GetFilesAsync();
    foreach (StorageFile sf in temp)   
    {
        if (sf.ContentType == "jpg")
            return true;
    }
    return false;
}