【问题标题】:Error Access to the path "/storage/emulated/0/abc.txt" is denied in Xamarin Android错误访问路径“/storage/emulated/0/abc.txt”在 Xamarin Android 中被拒绝
【发布时间】:2019-11-23 04:29:13
【问题描述】:

我正在尝试在 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_STORAGEWRITE_EXTERNAL_STORAGE 权限。

目标 Android 版本: Android 8.0 API Level 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 text) [0x000d1] in C:\ABC\XYZ\FileLogger_Android.cs:73 }

【问题讨论】:

  • 听起来您还没有明确请求用户许可,这里是example

标签: xamarin xamarin.android


【解决方案1】:

对于 >= 23 的版本,您需要提供运行时权限。您可以通过以下链接浏览文档。

https://devblogs.microsoft.com/xamarin/requesting-runtime-permissions-in-android-marshmallow/

或者现在为了测试,你可以去应用权限,允许存储权限。

【讨论】:

  • 太棒了,谢谢 sharmaji
猜你喜欢
  • 1970-01-01
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-04
  • 2022-07-17
相关资源
最近更新 更多