Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Writing to Android External Storage

I'm trying to copy an sqlite database file to an accessible location in the external storage.

Here's the code below:

`private void CopyDatabaseFile(string dbPath)
{
    var destPath = System.IO.Path.Combine(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath, "database.db");

    // Destination
    var destFile = new Java.IO.File(destPath);
    var canWrite = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).CreateNewFile();
    var canRead = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).CanRead();
    if (!destFile.Exists())
    {
        try
        {
            var result = destFile.CanWrite();
            destFile.CreateNewFile();
        }
        catch (Java.IO.IOException ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error Message: {ex.Message}");
            System.Diagnostics.Debug.WriteLine($"Error Source: {ex.Source}");
        }
    }
}`

This is catching a Java.IO.IOException and the error message is Permission denied.

Although i have tried enabling read / write permission for external storage in androidmanifest.xml like this:

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

However, i'm getting the same error message.

Any suggestion would be appreciated. :)

Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai
    edited November 2019

    @Ayobami
    First of all, make sure your create database path.

    I create sqlite database with following path.

    pdatabase = new PrijemDatabase(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Notes3.db3"));

    Then we can access the database path(System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "Notes3.db3");) and copy it by following code.

        [assembly: Dependency(typeof(GetDBFile))]
       namespace Notes.Droid
       {
        public class GetDBFile : CopyDB
      {
         public void copy()
       {
        string path = 
         System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), 
        "Notes3.db3"); 
    
        File f = new File(path);
        FileInputStream fis = null;
        FileOutputStream fos = null;
    
        fis = new FileInputStream(f);
        fos = new FileOutputStream("/mnt/sdcard/db_dump.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();
       }
      }
    

    Here is my answered link, you can refer to it(i test it in the android 8.1, it worked as normal).
    https://forums.xamarin.com/discussion/170906/how-do-i-locate-sqlite-file-for-android-in-xamarin-forms

    Note: If you want to open the DB, check the data, you just copy the Notes3.db3 is not enough. you should copy the Notes3.db3-shm as well

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    @Ayobami

    Do you want to have demo to make a test? Here is my demo. you can refer to it, please give the storage permission manually.

    Here is running gif

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    @Ayobami Do you have any update for this issue? If the reply is helpful, please mark it as answer, it will help others who have similar issue.

  • luguerrero10luguerrero10 Member

    @LeonLu said:
    @Ayobami

    Do you want to have demo to make a test? Here is my demo. you can refer to it, please give the storage permission manually.

    Here is running gif

    Amigo,Primero que todo muchas gracias por compartir sus conocimientos, llevaba mucho tiempo tratando de j¿hacer lo mismo que hiciste y fue fácil adaptarlo a mi código,le estoy agradecido pues soy relativamente muy nuevo con xamarin,espero seguir aprendiendo para compartir también mis conocimientos, su demo me funciono correctamente siguiendo los pasos de autorizar almacenamiento de forma manual.
    Saludos desde Colombia.

Sign In or Register to comment.