File.ReadAllText(): System.UnauthorizedAccessException: '对路径的访问被拒绝'

问题描述

这是我遇到问题的代码片段:

public OpenPage(string filePath,int? index,object jobject)
        {
            InitializeComponent();

            File.SetAttributes(filePath,FileAttributes.normal); // Here is where error in title occurs
            var readText = File.ReadAllText(filePath); // Also occurs here
            
            displayAlert("Alert",readText,"Ok");      
        }

我正在创建一个 UWP Xamarin.Forms 应用程序,它需要从选定目录(C: 驱动器上的任何内容)读取文件。虽然当我没有从本地缓存/AppData 中选择文件时,我在标题中遇到了错误

查看 StackOverflow 中的其他类似帖子(例如 Why is access to the path denied?)非常适合了解有关该主题的更多信息,尽管有关此错误的许多问题已经过时。

在上面的帖子中,有人说不能将目录作为 File.ReadAllText() 的参数传递。

有什么解决办法吗?我需要访问 C: 驱动器上的文件。供参考,我调试时构造函数中的filePath为“"C:\Users\ianpc\Desktop\config file clones\te0_ptt_wog.json"。

解决方法

有什么解决办法吗?我需要访问 C: 驱动器上的文件。供参考,我调试时构造函数中的filePath为“"C:\Users\ianpc\Desktop\config file clones\te0_ptt_wog.json"。

问题是 UWP 应用运行在沙盒环境中,所以我们不能使用 n 命名空间直接访问带路径的文件。

对于 xamarin 表单应用,我们建议您使用 Windows Storage api 访问带路径的文件,在此之前,您需要启用 k 功能。

例如

System.IO

实施

broadFileSystemAccess

使用

public interface FileAccessInterface
{
    Task<string> GetFileText(string filePath);
}

有关更多信息,请参阅此案例 reply