编程语言
首页 > 编程语言> > c#-UWP无法通过FolderPicker从硬盘驱动器访问文件夹

c#-UWP无法通过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;
}

标签:windows-10-universal,uwp,win-universal-app,file-access,c
来源: https://codeday.me/bug/20191027/1940614.html