Xamarin.Forms在文件系统中保存文件 [英] Xamarin.Forms Saving file in filesystem

查看:209
本文介绍了Xamarin.Forms在文件系统中保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从Web下载文件并保存到Environment.SpecialFolder的任何位置.不管我尝试哪种方法-我总是得到

System.UnauthorizedAccessException:'对路径'我尝试的任何可能路径(甚至超出Environment.SpecialFolder)的访问都被拒绝."

我尝试在UWP和Android上访问文件系统-两者都是相同的异常.

到目前为止,我没有碰到什么尝试:

  • 我尝试使用DependencyService通过PCL和每个平台分别进行此操作.
  • 检查文件夹是否为只读
  • 以管理员权限启动Visual Studio
  • 将调试更改为发布
  • 尝试过Xam.Plugins.DownloadManager

  • 代码示例:

    I try to download file from web and save to any of Environment.SpecialFolder locations. No matter of what approach I try - I always get

    System.UnauthorizedAccessException: 'Access to the path 'any possible path I try (even beyond Environment.SpecialFolder)' is denied.'

    I tried accessing filesystem on UWP and Android - both same exception.

    What I tried with no luck so far:

  • I tried to do this via PCL and via each platform individually using DependencyService.
  • Checked if folders are read-only
  • Started Visual Studio with administrator privileges
  • Changed Debug to Release
  • Tried Xam.Plugins.DownloadManager

  • Code sample:

    var webClient = new WebClient();
    webClient.DownloadDataCompleted += (s, e) => {
       var bytes = e.Result;
       string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
       string localFilename = "downloaded.jpg";
       string localPath = Path.Combine(documentsPath, localFilename);
       File.WriteAllBytes(localPath, bytes);
    };
    webClient.DownloadDataAsync(new Uri(url));
    

    推荐答案

    您正面临权限问题.

    首先,您必须添加AndroidManifest:

    First, you will have to add in your AndroidManifest:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    并且由于Android Marshmallow,您需要向用户询问权限,因此,我建议使用软件包权限插件

    And since Android Marshmallow, you need to ask the user for the permissions, so I advise to use the package Permissions.Plugin

    并添加您的MainActivity:

    And add in your MainActivity:

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    

    您可以通过以下方式签入运行时是否具有权限:

    You can check in runtime if you have the permissions by:

    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
        if (status != PermissionStatus.Granted)
        {
            if(await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
            {
                await DisplayAlert("Need storage, "Request storage permission", "OK");
            }
    
            var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
            //Best practice to always check that the key exists
            if(results.ContainsKey(Permission.Storage))
                status = results[Permission.Storage];
        }
    

    有关更多信息,您可以查看此博客文章,其中解释了Android中的所有权限- https://devblogs.microsoft.com/xamarin/requesting-runtime-permissions-in-android-marshmallow/

    For further information you can check this blog post explaining all the permissions in Android - https://devblogs.microsoft.com/xamarin/requesting-runtime-permissions-in-android-marshmallow/

    这篇关于Xamarin.Forms在文件系统中保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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