android - 仅在我的应用程序加载时第一次拒绝访问路径“/storage/emulated/0/log.txt”
问题描述
我正在生成txt
文件Xamarin.forms
。应用程序第一次在 Visual Studio 中同时执行请求权限并引发异常。
System.UnauthorizedAccessException
Message=Access to the path "/storage/emulated/0/log.txt" is denied.
从我第二次在手机中打开应用程序开始,它不会询问权限(正如我在崩溃前提供的那样)并生成 txt 文件。所以它工作正常。
为什么它在第一次执行时抛出错误?
这是我的代码
protected override void OnStart()
{
base.OnStart();
if ((int)Build.VERSION.SdkInt >= 23)
{
if (CheckSelfPermission(Manifest.Permission.AccessFineLocation) != Permission.Granted)
RequestPermissions(LocationPermissions, RequestId);
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
if (requestCode == RequestId)
{
if ((grantResults.Length == 1) && (grantResults[0] == (int)Permission.Granted))
{
///Premission granted by user
string filePath = string.Empty;
filePath = Android.OS.Environment.ExternalStorageDirectory.ToString();
var filename = System.IO.Path.Combine(filePath, "log" + ".txt");
}
else
{
///Permission denied by user
}
}
else
{
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
解决方案
您使用的路径是外部存储。如果要在Xamarin.forms中使用此路径,可以使用Dependency 服务。
创建接口 IExternalStorage:
public interface IExternalStorage
{
string GetPath();
}
Android 上的实现:请注意Android.OS.Environment.ExternalStorageDirectory
已弃用。
[assembly:Dependency(typeof(AndroidImplementation))]
namespace App.Droid
{
public class AndroidImplementation: IExternalStorage
{
public string GetPath()
{
Context context = Android.App.Application.Context;
var filePath = context.GetExternalFilesDir("");
return filePath.Path;
}
}
}
然后你可以在 Xamarin.Forms 中使用它:
var folderPath = DependencyService.Get<IExternalStorage>(). GetPath();
获取路径后,您可以使用下面的代码创建文件并输入一些字符串。
var filePath = DependencyService.Get<IExternalStorage>().GetPath();
var path = System.IO.Path.Combine(filePath, "log" + ".txt");
using (var writer = File.CreateText(path))
{
await writer.WriteLineAsync("hello");
}
//path: /storage/emulated/0/Android/data/com.companyname.app5/files/log.txt
推荐阅读
- python - 如何打印只打印python中字典的所有值?
- sh - 如何在管道开始时检测错误?
- sql - 使用 EXECUTE 评估 PL/pgSQL 中的动态条件
- sql - 如何将增量计数器添加到分组行,每次变量更改时重置计数器
- c++ - 由于变体成员 N3690/N4140 与 N4659/N4727 而删除了隐式定义的构造函数
- google-apps-script - 如何从 Google 表单项中获取验证模式
- c++ - 使用负数组索引访问前一个成员
- linux - Shell 脚本 - tar 命令将存档名称误认为是目录
- java - 如何将我的 Java 代码集成到具有标准 HTML、CSS、Javascript 的 Web 应用程序?
- sails.js - 将 Sails.js 中的所有 404 响应定向到单页应用程序的 index.html 静态资产?