SpecialFolder.Personal existing sqlite database

别说谁变了你拦得住时间么 提交于 2021-02-11 13:28:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!