我正在尝试在Android 8 API Level 26模拟器上运行Xamarin Android应用。当我尝试将日志写入文件时,它给出了异常。
例外:
System.UnauthorizedAccessException:访问路径 “ /storage/emulated/0/abc.txt”被拒绝
代码:
string filename = "abc.txt";
var documentsPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = Path.Combine(documentsPath, filename);
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(text);
}
我还授予了READ_EXTERNAL_STORAGE
和WRITE_EXTERNAL_STORAGE
权限。
目标Android版本: Android 8.0 API级别26 Oreo
异常详细信息:
{System.UnauthorizedAccessException:访问路径 “ /storage/emulated/0/NECMobilePos_log21092018.txt”被拒绝。在 System.IO.FileStream..ctor(System.String路径,System.IO.FileMode 模式,System.IO.FileAccess访问权限,System.IO.FileShare共享, System.Int32 bufferSize,System.Boolean匿名, System.IO.FileOptions选项)中的[0x001aa] /Users/builder/jenkins/workspace/xamarin-android-d15-6/xamarin-android/external/mono/mcs/class/corlib/System.IO/FileStream.cs:239 在System.IO.FileStream..ctor(System.String路径,System.IO.FileMode 模式,System.IO.FileAccess访问权限,System.IO.FileShare共享, System.Int32 bufferSize,System.Boolean isAsync,System.Boolean 匿名)[0x00000]在 /Users/builder/jenkins/workspace/xamarin-android-d15-6/xamarin-android/external/mono/mcs/class/corlib/System.IO/FileStream.cs:149 在System.IO.FileStream..ctor(System.String路径,System.IO.FileMode 模式,System.IO.FileAccess访问)[0x00000]在 /Users/builder/jenkins/workspace/xamarin-android-d15-6/xamarin-android/external/mono/mcs/class/corlib/System.IO/FileStream.cs:86 在(包装器远程调用并检查) System.IO.FileStream..ctor(字符串,System.IO.FileMode,System.IO.FileAccess) 在NECMobilePOS.Client.DroidLatest.FileLogger_Android.SaveText (System.String filenamePassed,System.String文本)在[0x000d1]中 C:\ ABC \ XYZ \ FileLogger_Android.cs:73}
答案 0 :(得分:2)
对于版本== 23,您需要提供运行时权限。您可以通过下面的链接浏览文档。
https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/
或者现在进行测试,您可以转到应用程序权限并允许存储权限。