在 C# 中打开文件访问被拒绝
我正在尝试读取文本文件的内容,但我收到类型为System.UnauthorizedAccessException"的访问路径被拒绝"异常.我尝试了以下方法:
I am trying to read the content of a text file but I get the 'Access to the path is denied' exception of type 'System.UnauthorizedAccessException'. I've tried the following:
- 在管理员模式下运行 Vs
- 检查文件是否只读
- 检查文件是否隐藏
- 检查文件是否对所有用户具有完全控制权
我的代码:
private async void MyButton_Click(object sender, RoutedEventArgs e)
{
string path = @"fullpath\TextFile.txt";
await Task.Run(() =>
{
string text = File.ReadAllText(path);
});
}
您无法像在 Windows 应用商店应用中那样访问所有文件.请查看此 MSDN 页面 以获取以下列表允许您的应用使用的位置.此外,要使用其中的大部分,您必须声明合适的Capabilities.如果您的文件不在此列表中和/或您尚未声明功能,您将收到 UnauthorizedException.
You can't access all your files just like that in Windows Store apps. Please take a look at this MSDN page for list of locations, which your app is permited to use. Also to use most of them you will have to declare suitable Capabilities. If your file is outside this list and/or you haven't declared capabilities, you will get UnauthorizedException.
一般商店应用程序不应在用户不知情的情况下访问文件 - 这是设计使然.如果你想在以后访问文件,你可以选择一个文件 FileOpenPicker 然后通过 FutureAccessList访问它a> 或 MostRecentlyUsed.
Generaly store apps shouldn't access files without user knowing about it - this is by design. If you want to access file in future, you can for example pick a file with FileOpenPicker and then access it by FutureAccessList or MostRecentlyUsed.