[FIXED] Unable to Export Sqlite database from SpecialFolder.ApplicationData to SD Card Xamarin Forms

Issue

I am currently developing an app that uses the sqlite-net database. I am trying to copy/export the database to my SD Card. When I run the code I get a System.NullRefrenceException: ‘Object reference not set to an instance of an object.’

I have tried several solutions but I always get the same exception. The issues occurs at the System.IO.File.WriteAllBytes(fileCopyName, bytes); Please help.

 private void CopyDBButton_Clicked(object sender, EventArgs e)
        {
            var basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var finalPath = Path.Combine(basePath, "Mydatabase");
            CopyDatabase(finalPath);
        }

 public static void CopyDatabase(string databasePath)
        {

            var bytes = System.IO.File.ReadAllBytes(databasePath);
            var fileCopyName = string.Format("/sdcard/Database_{0:dd-MM-yyyy_HH-mm-ss-tt}.db", System.DateTime.Now);
            System.IO.File.WriteAllBytes(fileCopyName, bytes);
        }

Solution

The issue was the path address. I fixed it by checking for the directory first to see if it exists, then I copy the database to the directory in a new/existing file. The issue I have now is that the file saves to phone but not the SD card, but I am just happy that the backup file is finally saving.
Below is the code is used to fix the issue:

    private void CopyDBButton_Clicked(object sender, EventArgs e)
    {
        //Used to find the database in the special folder
        string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Mydatabase");

        //Used to locate the SD Card path
        string path1 = Path.Combine("/sdcard/", Android.OS.Environment.DirectoryDownloads);

        //Used to save the Database to a byte array
        var bytes = File.ReadAllBytes(path);

        //Used to check if the directory exists
        if (!Directory.Exists(path1))
        {
            //Directory.CreateDirectory(filePathDir);
            Console.WriteLine("Doesnt Exist");
        }
        else
        {
            Console.WriteLine("Does Exist");

            //Used to create the name of the new Database backup file
            var fileCopyName = string.Format(path1 + "/Database_{0:dd-MM-yyyy_HH-mm-ss-tt}.db", DateTime.Now);

            //Write to the new database backup file
            File.WriteAllBytes(fileCopyName, bytes);
        }
    }

Answered By – Adrian Hurst

Answer Checked By – Cary Denson (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published