应用程序第二次运行时拒绝访问文件 [英] Access to file denied on app's second run

查看:42
本文介绍了应用程序第二次运行时拒绝访问文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用代码访问 SD 卡上的文件时遇到一个奇怪的问题:

I'm facing a weird issue, when trying to access file on SD card with code:

var path = @"D:\Test\test.txt";
try
{
    StorageFile file = await StorageFile.GetFileFromPathAsync(path);
}
catch (Exception ex) { Debug.WriteLine($"File access failed due to {ex.Message}"); }

path = @"Test\test.txt";
StorageFile file2 = await (await KnownFolders.RemovableDevices.GetFoldersAsync()).FirstOrDefault().GetFileAsync(path);

文件在 SD 卡上,我已经声明了 RemovableStorage 功能,并添加了 FileTypeAssociation.我可以在第一次调试应用程序时获取该文件,但是在第二次运行时,第一个 StorageFile 出现了 UnauthorizedException.令人惊讶的是,通过 RemovableStorage 获取文件的第二次尝试每次都有效.如果我只重新启动手机并再次调试应用程序 - 它会再次工作,但仍然只是第一次.

The file is on SD card, I've declared RemovableStorage capability, and added FileTypeAssociation. I can get the file when I first debug the app, but on the second run I get UnauthorizedException with the first StorageFile. Amazingly the second try to get the file via RemovableStorage works every time. If I only restart the phone and debug app once again - it will again work, but still only for the first time.

通过 StorageFile.GetFileFromPathAsync() 访问文件是否受到某种限制?我错过了什么吗?

Is accessing files by StorageFile.GetFileFromPathAsync() somehow limited? Am I missing something?

更新:

似乎在最新版本的模拟器 10856 上我每次运行都会遇到异常,这可能意味着无法通过完整路径访问文件.

Seems like on newest version of emulator 10856 I get an exception on every run, what may mean that there will be no way to access file via full path.

推荐答案

选择器允许访问,因为用户向您提供了文件,而不是路径.winstore 应用程序不应依赖于用户驱动器/文件夹布局,这就是您无权通过绝对路径访问文件的原因.在这种情况下,我们应该首先在 manifest 文件中允许访问可移动设备,然后我们应该使用系统的 RemovebleDevices 文件夹来访问允许类型的文件.

The picker allows access because the user provided the file to you, not the path. A winstore app should not be dependent upon a users drive / folder layout, that is why you don't have authority to access files by absolute path. In this case, we should firstly allow access to removable devices in manifest file, then we should use system's RemovebleDevices folder to access files of allowable types.

同样奇怪的是,您第一次可以使用绝对路径.在我的测试设备中,如果使用绝对路径,我总是会收到 UnauthorizedAccessException 和访问被拒绝"错误.我的设备是构建 10586.11.

Also it is strange you can work with the absolute path the first time. In my test device, I always get the UnauthorizedAccessException and "Access is denied" error if using absolute path. My device is of build 10586.11.

这篇关于应用程序第二次运行时拒绝访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆