问题
On my Xamarin android application i create db path using the "System.Environment.SpecialFolder.Personal". I have an existing sqlite database. Where in the project and with what properties must i include the database to be used in the peronal folder?
回答1:
You can use Xamarin.Essentials
to access your read-only bundle/asset resource and copy it without have to use native platform code or if you are coding within an Xamarin.Android project, you can directly use Android.Content
's Assets
So assuming you have a database in your Android Assets folder:
Assets
db.sqlite
Xamarin Essentials / NetStd2.0 Code Example:
var copyToLocationPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "db.sqlite");
if (!File.Exists(copyToLocationPath))
{
using (var assetStream = await Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync("db.sqlite"))
using (var fileStream = new FileStream(copyToLocationPath, FileMode.Create, FileAccess.Write))
{
await assetStream.CopyToAsync(fileStream);
}
}
var connection = new SqliteConnection(copyToLocationPath);
Xamarin Android code sample (Directly use Assets
):
var copyToLocationPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "db.sqlite");
if (!File.Exists(copyToLocationPath))
{
using (var assetStream = Assets.Open("db.sqlite"))
using (var fileStream = new FileStream(copyToLocationPath, FileMode.Create, FileAccess.Write))
{
await assetStream.CopyToAsync(fileStream);
}
}
来源:https://stackoverflow.com/questions/55031866/specialfolder-personal-existing-sqlite-database