Xamarin.forms备份SQLite数据库

马塞尔·德尔海(Marcel Delhaye)

我的Xamarin.forms应用程序(Android)集成了一个SQLite数据库,这要归功于我在此处找到的示例所能正确管理的数据库:https : //docs.microsoft.com/fr-fr/xamarin/get-started/quickstarts/database

我的第一个问题是:如何保存这个notes.db3文件(在Onedrive或可能的Google驱动器上)。

我的第二个问题:如何为应用程序提供包含包含数据表的数据库。从Internet上了解到,我知道您需要将预填充的文件sqlite.db3复制到Resources文件夹,然后将此文件和代码复制到application文件夹。

我进行了很多搜索,但是找不到能够执行此操作的确切代码。感谢您的帮助,这将非常有用,因为关于此主题的文档很少。

编辑:这是第二个问题的答案:

  1. 当新用户首次运行该程序时,我使用该程序用有用的数据填充表格。
  2. 我以编程方式将SQLite文件复制到可通过外部应用程序访问的文件夹中:Android Studio(Visual Studio 2019中Android设备监视器实用程序的文件管理器不起作用!)。这是代码:

using Xamarin.Essentials;
using FileSystem = Xamarin.Essentials.FileSystem;

public void CopyDBToSdcard(string dbName)
        {
            var dbPath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), dbName));
            string destPath = Path.Combine("/sdcard/Android/data/com.aprisoft.memocourses/files", dbName);
            //
            if (File.Exists(dbPath))
            {
                if (File.Exists(destPath))
                {
                    File.Delete(destPath);
                }
                File.Copy(dbPath, destPath);
            }
        }

  1. 我将此预填充的SQLite文件复制到主项目根目录的应用程序中。在此文件的属性中,我在“构建操作”中指示“嵌入式资源”。

  2. 程序首次运行时,它将检查是否找到SQLite文件。如果找不到它,我将使用Dirk在此处提供的代码将文件复制到特殊文件夹“ LocalApplicationData”中,这是代码:

public void CopyDB_FR(string filename)
        {
            var embeddedResourceDb = Assembly.GetExecutingAssembly().GetManifestResourceNames().First(s => s.Contains(filename));
            var embeddedResourceDbStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResourceDb);

            var dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), filename);
            //
            if (!File.Exists(dbPath))
            {
                using (var br = new BinaryReader(embeddedResourceDbStream))
                {
                    using (var bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
                    {
                        var buffer = new byte[2048];
                        int len;
                        while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            bw.Write(buffer, 0, len);
                        }
                    }
                }
            }

        }

我将线程保持打开状态,因为我还没有第一个问题的答案。任何帮助将不胜感激。谢谢。

编辑2:我遵循Microsoft的示例,使用Graph API将与Azure的连接建立到我的应用程序中,并且它的工作原理是:连接很好,我可以检索用户数据。但是,我找不到将文件复制到Onedrive的方法。我正在使用以下代码:

await (Application.Current as App).SignIn();
            btnConnect.IsEnabled = false;
            //
            // put user's files
            
            string path = Path.Combine("/data/data/com.ApriSoft.memocourses/files/Backup", "MemoCourses.db3");
            byte[] data = System.IO.File.ReadAllBytes(path);
            Stream stream = new MemoryStream(data);
            
            await App.GraphClient.Me
                    .Drive
                    .Root
                    .ItemWithPath("/Backup/MemoCourses.db3")
                    .Content
                    .Request()
                    .PutAsync<DriveItem>(stream);

            ;

但是几分钟后,出现以下错误:

身份验证错误代码:GeneralException消息:发送请求时发生错误。

我的代码不正确吗?请帮助我,我想完成我的应用程序。非常感谢你。

马塞尔·德尔海(Marcel Delhaye)

我终于设法备份并将SQLite数据库还原到OneDrive。它既简单又复杂。如果您遵循此处随Graph和Azure提供的Microsoft示例,这很简单:https : //docs.microsoft.com/en-us/graph/tutorials/xamarin? tutorial-step =1而且它很复杂,因为此示例未解释如何将文件复制到OneDrive。这是我做的事情:我按照Microsoft的分步示例将其应用于应用程序。

在Azure管理中心中,我添加了配置的权限:

Device.Read
Files.ReadWrite.All
Files.ReadWrite.AppFolder

后者是最重要的。

在我的应用程序中:在OAuthSettings.cs中,通过将Files.ReadWrite.AppFolder添加到Scopes常量的定义来修改以下行:

Public const string Scopes = "User.Read Calendars.Read Files.ReadWrite.AppFolder";

要访问OneDrive上的应用程序文件夹,这非常重要。在与SQLite数据库备份相对应的方法中,以下是放置的代码:

Stream contentStream = null;
//
var path = await App.GraphClient
                        .Me
                        .Drive
                        .Special
                        .AppRoot
                        .ItemWithPath("MemoCourses.db3")
                        .Request()
                        .GetAsync();


//
try
{
    //foundFile = await path.Request().GetAsync();
    if (path == null)
    {
        await DisplayAlert("Attention", "Backup file not found", "OK");
    }
    else
    {
        contentStream = await App.GraphClient.Me
                                    .Drive
                                    .Special
                                    .AppRoot
                                    .ItemWithPath("MemoCourses.db3")
                                    .Content
                                    .Request()
                                    .GetAsync();

         
        var destPath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), dbName));
        var driveItemFile = System.IO.File.Create(destPath);
        contentStream.Seek(0, SeekOrigin.Begin);
        contentStream.CopyTo(driveItemFile);
        //
    }
}
catch (Exception ex)
{
    var error = ex;
    await DisplayAlert("Attention", error.ToString(), "OK");
}

dbName包含SQLite文件的名称。

为了还原数据库:

var dbPath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), dbName));
byte[] data = System.IO.File.ReadAllBytes(dbPath);
Stream stream = new MemoryStream(data);
//
try
{
    await App.GraphClient.Me
        .Drive
        .Special
        .AppRoot
        .ItemWithPath("MemoCourses.db3")
        .Content
        .Request()
        .PutAsync<DriveItem>(stream);
}
catch
{
    await DisplayAlert("Attention", "Problem during file copy...", "OK");
}

在我的应用程序中,一切正常。我希望我已经帮助那些仍在寻找解决此问题的人。如果您需要更多信息,请随时向我提问。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用Xamarin.Forms从Sqlite数据库获取数据

为 Xamarin.Forms 下载哪个 SQLite 数据库

Xamarin SQLite数据库的Gui

数据库sqlite中的项目未更新(Xamarin.Forms)

在每个App Release Xamarin Forms之后更新/维护SQLite数据库

Android-无法在Xamarin.forms中打开数据库(SQLite异常)

带有Xamarin.Forms应用程序的SQLite.net数据库

将日期时间插入SQLite数据库Xamarin.Forms

将sqlite数据库从android studio应用迁移到Xamarin.Forms应用

从Web API将数据插入SQLite数据库后,为什么Xamarin.Forms应用程序崩溃?

如何从Xamarin中的SQLite数据库删除数据

如何在跨平台应用程序的Xamarin Forms中将图像存储在sqlite数据库中?

SQLite.SQLiteException:xamarin.forms 应用程序中的数据库磁盘映像格式不正确

Visual Studio + Xamarin:创建数据库SQLite

Xamarin iOS找不到SQLite数据库的路径

Xamarin Visual Studio Android设置SQLITE数据库

SQLite Xamarin表单数据库表到ListView

在Xamarin的SQLite数据库中存储和检索数组

在Xamarin.iOS中查看Sqlite数据库

Xamarin 检查数据库 Sqlite 中是否存在列

Xamarin Forms + Firebase - 在允许读/写数据之前通过数据库验证用户 uid

Xamarin/C# - 为多个表以编程方式将数据插入 SQLite 数据库?

如何从Xamarin中的SQLite数据库显示CollectionView中的数据?

Xamarin.Forms应用程序SQL Server数据库选项

如何从Xamarin.Forms上的Firebase实时数据库获取ID节点(密钥)

Database.EnsureCreated似乎不是在创建数据库(xamarin.forms)

如何在 Xamarin.Forms 中复制本地数据库?

如何在Xamarin Forms中访问数据库表中的字段

在Xamarin.Forms中直接访问Sql Server数据库