微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Xamarin 表单,myDir.Mkdir();在 Android 项目中返回 false

如何解决Xamarin 表单,myDir.Mkdir();在 Android 项目中返回 false

我需要在我设备的公共外部存储中创建一个文件夹和文件,这里是我的代码

安卓清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.MyApp">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="29" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application android:label="MyApp.Android" android:theme="@style/MainTheme">

    <provider
           android:name="androidx.core.content.FileProvider"
           android:authorities="${applicationId}.provider"
           android:exported="false"
           android:grantUriPermissions="true">
      <Meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/provider_paths" />
    </provider>
  </application>
</manifest>

SaveAndroid.cs(在 Android 项目中)

string exception = string.Empty;
        string root = null;

        //Get the root path in android device.
        if (Android.OS.Environment.IsExternalStorageEmulated)
        {
            root = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath,Android.OS.Environment.DirectoryDownloads);
        }
        else
        {
            root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
        }

        //Create directory and file 
        Java.IO.File myDir = new Java.IO.File(root + "/PDFChantier");
        bool created = myDir.Mkdir();
        Java.IO.File file = new Java.IO.File(myDir,fileName);

但是 myDir.Mkdir() 总是返回 false,当我安装我的应用程序时,它要求写访问权限,所以权限应该没问题。

我确定我错过了一些愚蠢的东西,但我已经尝试了所有 StackOverflow 和 Google 的答案,但没能成功

感谢您的帮助!

编辑:刚刚找到解决方案,发布后 10 分钟......

对于 Android 10 及更新版本,我们需要使用

  string newRoot = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
        Java.IO.File newMyDir = new Java.IO.File(newRoot + "/PDFChantier");
        bool newCreated = newMyDir.Mkdir();

如果这可以帮助某人:)

解决方法

我找到了解决方案:

对于 Android 10 及更新版本,我们需要使用

string newRoot = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
        Java.IO.File newMyDir = new Java.IO.File(newRoot + "/PDFChantier");
        bool newCreated = newMyDir.Mkdir();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。