首页 > 解决方案 > 仅在我的应用程序加载时第一次拒绝访问路径“/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);
    }
}

标签: androidxamarinxamarin.forms

解决方案


您使用的路径是外部存储。如果要在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

在此处输入图像描述


推荐阅读