iamlawrencev
iamlawrencev

Reputation: 158

How to access an SQLite database under the Android app sandbox storage?

I have a native app which generates an SQLite database file in the com.companyname.appname/databases/MyDatabase.db. This is in the internal app storage of Android.

I need to migrate this app into Xamarin.Forms but I need to access that database either to move it to another directory or read the database directly.

The problem is that using the System.Environment.SpecialFolder.Personal / System.Environment.SpecialFolder.MyDocuments which is the highest possible location as said in the documentation here only results in the com.companyname.appname/files/ location. I need to go one level higher to access the database folder. Is this possible?

Note: I have tried hardcoding the path, and also adding "../" which doesn't work and throws an error.

Upvotes: 1

Views: 820

Answers (1)

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10978

The problem is that using the System.Environment.SpecialFolder.Personal / System.Environment.SpecialFolder.MyDocuments which is the highest possible location as said in the documentation here only results in the com.companyname.appname/files/ location.

The Personal directory that serves as a common repository for documents is equivalent to MyDocuments. For more information, you could check the MS docs. https://learn.microsoft.com/en-us/dotnet/api/system.environment.specialfolder?view=netframework-4.8

A simple way to read database with Personal folder.

string databaseFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                string databasePath = Path.Combine(docFolder, "TodoSQLite2.db3");

Copy the exited database to Assets folder.

enter image description here

And set the Build Action to AndroidAsset.

enter image description here

Updated:

If you want to copy the database to another folder at runtime, you could try the code below. I use local folder for example.

// Check if it exists at that path
if (File.Exists(filePath))
{
   // Copy the file to the app's local folder, you could change the path where you want to copy.
   string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
   string destinationPath = Path.Combine(folderPath, "myData.db");
   File.Copy(filePath, destinationPath);
}

Upvotes: 0

Related Questions