2016-06-12 197 views
3

我想使用UWP应用程序从本地硬盘(包括子文件夹)中的某个文件夹中读取所有图像文件。UWP无法通过FolderPicker访问硬盘中的文件夹

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

,然后我m得到下一个异常:

mscorlib.ni中发生类型'System.UnauthorizedAccessException'异常。 dll,但未在用户代码中处理 WinRT信息:无法访问指定的文件或文件夹(D:\ test)。该项目不在应用程序有权访问的位置(包括应用程序数据文件夹,可通过功能访问的文件夹以及StorageApplicationPermissions列表中的持久项目)。验证该文件未标有系统或隐藏的文件属性。

那么我怎样才能访问从文件夹中读取文件?

感谢。

+0

那么,你*“验证该文件未标有系统或隐藏文件属性“*?您是否验证过,根据应用程序的完整性级别和授权,路径是可访问的? – IInspectable

+0

相关信息:[文件访问权限](https://msdn.microsoft.com/en-us/windows/uwp/files/file-access-permissions)。 – IInspectable

回答

3

从文件选取器中获取文件夹后,可能无法通过其路径访问该文件夹。您需要直接使用返回的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; 
}