![](/img/trans.png)
[英]C# access to the path is denied…(System.UnauthorizedAccessException: Access to the path 'C:\' is denied.)
[英]File.ReadAllText(): System.UnauthorizedAccessException: 'Access to the path is denied.'
这是我遇到问题的代码片段:
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");
}
I'm creating a UWP Xamarin.Forms application which needs to read a file from a selected directory (anything on the C: drive). 虽然当我不从本地缓存/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 应用程序在沙盒环境中运行,所以我们不能使用System.IO
命名空间直接访问带有路径的文件。
对于 xamarin forms 应用程序,我们建议您使用broadFileSystemAccess
存储 api 以访问文件的能力。
例如
public interface FileAccessInterface
{
Task<string> GetFileText(string filePath);
}
执行
[assembly: Dependency(typeof(FileAccessInterfaceImplementation))]
namespace XamarinPicker.UWP
{
public class FileAccessInterfaceImplementation : FileAccessInterface
{
public async Task<string> GetFileText(string filePath)
{
var stringContent = "";
try
{
var file = await StorageFile.GetFileFromPathAsync(filePath);
if (file != null)
{
stringContent = await Windows.Storage.FileIO.ReadTextAsync(file,Windows.Storage.Streams.UnicodeEncoding.Utf8);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return stringContent;
}
}
}
用法
var text = await DependencyService.Get<FileAccessInterface>().GetFileText(@"C:\Users\xxxx\Desktop\test.txt");
有关更多信息,请参阅此案例回复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.