I need to create a folder and file in the public external storage of my device, here my code:
Android Manifest
<?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
in Android project:
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);
But myDir.Mkdir()
always returns false. When I install my app, it's asking for the write access so the right should be ok.
I am sure I am missing something stupid, but I already tried all StackOverflow and Google answer, and didn't manage to make it work.
I found the solution:
For Android 10 and newer, we need to use:
string newRoot = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
Java.IO.File newMyDir = new Java.IO.File(newRoot + "/PDFChantier");
bool newCreated = newMyDir.Mkdir();