gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:21:19 26 4
gpt4 key购买 nike

我想使用 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并保留返回的 token :

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;
}

关于c# - UWP 无法通过 FolderPicker 从硬盘访问文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37776007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com