I'm trying to export files to the public external storage of an Android phone in Xamarin, for a backup DB. However, in the last version of Android phones (11.0 - API30
), one can't opt-out of scoped storage using the property android:requestLegacyExternalStorage="true"
of the <application>
tag in the manifest.xml
.
I made sure that the permissions READ_EXTERNAL_STORAGE
& WRITE_EXTERNAL_STORAGE
are granted before trying to create the file. Still, when trying to create a file, a System.UnauthorizedAccessException
exception is thrown.
/* file 1: */
// ....
private async void Export_Tapped (object sender, EventArgs e) {
// check if permission for writing in external storage is given
bool canWrite = await FileSystem.ExternalStoragePermission_IsGranted ();
if (!canWrite) {
// request permission
canWrite = await FileSystem.ExternalStoragePermission_Request ();
if (!canWrite) {
// alert user
return;
}
}
// find the directory to export the db to, based on the platform
string fileName = "backup-" + DateTime.Now.ToString ("yyMMddThh:mm:ss") + ".db3";
string directory = FileSystem.GetDirectoryForDatabaseExport (); // returns "/storage/emulated/0/Download"
string fullPath = Path.Combine (directory, fileName);
// copy db to the directory
bool copied = false;
if (directory != null)
copied = DBConnection.CopyDatabase (fullPath);
if (copied)
// alert user
else
// alert user
}
// ....
/* file 2: */
class DBConnection
{
private readonly string dbPath;
// ....
public bool CopyDatabase(string path)
{
byte[] dbFile = File.ReadAllBytes(dbPath);
File.WriteAllBytes(path, dbFile); // --> this is where the exception is thrown <--
return true;
}
// ....
}
So the question stands: how does one write a new file to the public external storage of an Android device with an API level of 29 or more?
All the resources I have found so far, maybe you can gather more information than I did:
- https://forums.xamarin.com/discussion/179999/access-denied-to-external-storage
- (regarding private external storage) https://forums.xamarin.com/discussion/171039/saving-files-to-external-storage
- https://learn.microsoft.com/en-us/xamarin/android/platform/files/external-storage?tabs=windows
- https://developer.android.com/about/versions/11/privacy/storage#permissions
The path you use is incorrect, please try the following file path .
Refer to https://forums.xamarin.com/discussion/comment/422501/#Comment_422501 .