0

I want to implement backup and restore database in android with xamarin android C#. My database is Sqlite and I want to backup db to SdCard. AnyOne Can Help Me? The code below is some My code

string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

    public bool createDataBase()
    {
        try
        {
            using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Plans.db")))
            {
                connection.CreateTable<Plan>();
                return true;
            }
        }
        catch (SQLiteException ex)
        {

            Log.Info("SQLiteEx", ex.Message);
            return false;
        }
    }
omid-ahmadpour
  • 63
  • 1
  • 12

1 Answers1

0

Use the below code

  var dbFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  var dbFile = System.IO.Path.Combine(dbFolder, "my_test.sqlite");
  var filename = System.IO.Path.Combine(GetLoggerDir(), "my_test.sqlite");

  FileStream readStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Read);
  FileStream writeStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
  ReadWriteStream(readStream, writeStream);

GetLoggerDir() method

  public static string GetLoggerDir()
    {
        Java.IO.File dataDir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/" + "YourFolderName" + "/");
        if (!dataDir.Exists())
            dataDir.Mkdirs();
        return dataDir.ToString();
    }

Add permissions in Manifest file

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

Also add runtime permission

A folder will create with name "YourFolderName" in the device sdCard. First copy that file to any other folder of the device then we can copy to PC for the specific purpose. I hope it will work perfectly.

Faiz Anwar
  • 658
  • 2
  • 9
  • 18