Reputation: 35
I want to generate a db for user so he can backup it. I've come up with this code:
private async void ExportButton_Clicked(object sender, EventArgs e)
{
var dest = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filePath = System.IO.Path.Combine(dest, "SpotterBackup.db3");
if (File.Exists(_dbPath))
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.Copy(_dbPath, filePath);
}
}
But thats write just to internal storage, I have searched for some solution and I've just found some java lang solution. How can I save db to external storage in xamarin?
Upvotes: 0
Views: 801
Reputation: 9234
You can try to use following code to copy the DB file to the external path. I copy the db file to download folder.
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.IO;
using Notes.Droid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
[assembly: Dependency(typeof(GetDBFile1))]
namespace Notes.Droid
{
class GetDBFile1 : ICopyDB
{
public void copy()
{
// My Db orignal file path string path1 = "/data/user/0/com.companyname.Notes/files/Notes3.db";
string path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Notes3.db3");
File f = new File(path);
FileInputStream fis = null;
FileOutputStream fos = null;
fis = new FileInputStream(f);
fos = new FileOutputStream("/storage/emulated/0/Download/databasename.db");
while (true)
{
int i = fis.Read();
if (i != -1)
{ fos.Write(i); }
else
{ break; }
}
fos.Flush();
Toast.MakeText(Android.App.Application.Context, "DB dump OK", ToastLength.Short).Show();
fos.Close();
fis.Close();
}
}
}
And add android:requestLegacyExternalStorage="true"
in <application>
tag of AndroidManifest.xml
.
Here is running screenshot.
Note: If run this code in android 11 or later, Google has not allowed application to access external folder and requestLegacyExternalStorage
will be ignored.
Apps that run on Android 11 but target Android 10 (API level 29) can still request the requestLegacyExternalStorage attribute. This flag allows apps to temporarily opt out of the changes associated with scoped storage, such as granting access to different directories and different types of media files. After you update your app to target Android 11, the system ignores the requestLegacyExternalStorage flag.
See the topic Manage device storage
Starting in Android 11, apps that use the scoped storage model can access only their own app-specific cache files. If your app needs to manage device storage
So, we cannot write a file to the public external storage in android 11 or later(like iOS's sandbox design).
Upvotes: 1