Xamarin.Forms 如何备份 SQLite 数据库

3

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

我的第一个问题是:如何将此notes.db3文件保存在Onedrive或可能的Google Drive上。

我的第二个问题是:如何提供包含数据表的数据库给应用程序。从我在互联网上找到的内容来看,您需要将预填充的文件sqlite.db3复制到资源文件夹中,然后使用代码将此文件复制到应用程序文件夹中。

我搜索了很多,但找不到确切的代码以便能够完成它。 感谢您的帮助,这将非常有用,因为这个主题的文档非常少。

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

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

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: 我遵循了微软的示例,使用Graph APIs在我的应用程序中构建了连接到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 消息:发送请求时发生错误。

我的代码有问题吗? 请帮助我,我想完成我的应用程序。非常感谢。


  1. 为什么你想要把notes.db3保存到服务器端?你在文档中提到的db是一个本地数据库,将存储在你的应用程序中。
  2. 将预填充文件sqlite.db3放入您的Android项目并获取特定文件路径,然后您可以通过文件路径打开/更新db文件。
- nevermore
你好,杰克。我在示例中引用了notes.db3文件以使其简单,但我的应用程序有一个SQLite文件,其中的数据是用户的数据。该文件存储在/data/user/0/com.aprisoft.memocourses/files/中,名称为MemoCourses.db3。这是我想保存到OneDrive的文件,但我不知道如何访问它,或者如何将其复制到OneDrive。谢谢你的帮助。 - Marcel Delhaye
看起来你在这个帖子中得到了解决方案,你也可以在这里分享答案:)。 - nevermore
1个回答

2
我终于成功地将我的SQLite数据库备份并恢复到OneDrive中了。这既简单又复杂。如果你遵循Microsoft在这里提供的Graph和Azure示例,它就很简单:https://learn.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");
}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接