使用 FileStream 写入文件时 Xamarin Forms 访问被拒绝 [英] Xamarin Forms access denied when writing to file with FileStream

查看:72
本文介绍了使用 FileStream 写入文件时 Xamarin Forms 访问被拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在真实的 Android 设备 (Android 8.0 - API 26) 上运行应用程序时,我试图将字符串附加到位于 .NET 共享项目中的文本文件,但出现此运行时错误:

I'm trying to append a string to a text file located within a .NET shared project while running the app on a real Android device (Android 8.0 - API 26), but I'm getting this runtime error:

System.UnauthorizedAccessException: Access to the path 
"/Namespace.Folder.FileName.txt" is denied.

导致错误的代码:

string filename= "Namespace.Folder.FileName.txt";
FileStream fs = null; fs = File.Open(filename, FileMode.Append);
StreamWriter sw = new StreamWriter(fs); sw.Write(text)

我在 Android 权限下检查了 ACCESS_COARSE_LOCATION 和 ACCESS_FINE_LOCATION,并且文本文件的构建操作设置为嵌入式资源.我试过使用 System.IO.File 并且它工作正常,但是这样我不知道如何不覆盖文本文件

I have both ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION checked under Android permissions and the text file's build action is set to Embedded Resource. I've tried using System.IO.File and it's working fine, but this way I don't know how not to overwrite the text file

var documentsPath = 
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, filename); 
System.IO.File.WriteAllText(filePath, text);

我想我的问题是将文本存储在位于共享项目中的文本文件中而不覆盖它的最佳方法是什么?

I guess my question is what's the best way to store text in a text file located within the shared project without overwriting it?

推荐答案

我发现了我的问题,我没有将根文件夹传递给作者和读者.工作代码:

I found my problem, I wasn't passing in the root folder to the writer and reader. Working code:

加载:

var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        var filePath = Path.Combine(documentsPath, filename);
        using (var streamReader = new StreamReader(filePath))
        {
            string content = streamReader.ReadToEnd();
            return content;
        }

写:

var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        var filePath = Path.Combine(documentsPath, filename);
        using (var streamWriter = new StreamWriter(filePath, true))
        {
            streamWriter.WriteLine(text);
        }

这篇关于使用 FileStream 写入文件时 Xamarin Forms 访问被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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