Xamarin.forms 备份 SQLite 数据库
Xamarin.forms Backup a SQLite database
我的 Xamarin.forms 应用程序 (Android) 集成了一个 SQLite 数据库,由于我在此处找到的示例,我可以正确管理它:https://docs.microsoft.com/fr-fr/xamarin/get-started/quickstarts/database
我的第一个问题是:如何保存这个 notes.db3 文件(在 Onedrive 或 Google 驱动器上)。
我的第二个问题:如何为应用程序提供包含数据表的数据库。我在网上了解到,您需要将预填充的文件sqlite.db3复制到Resources文件夹,然后将这个带有代码的文件复制到application文件夹。
我搜索了很多,但找不到能够做到这一点的确切代码。
谢谢你帮助我,这将非常有用,因为关于这个主题的文档很少。
编辑:
这是第二个问题的答案:
- 当新用户第一次使用该程序 运行 时,我使用该程序用有用的数据填充表格。
- 我以编程方式将 SQLite 文件复制到可通过外部应用程序访问的文件夹中:Android Studio(Android Device Monitor 实用程序的文件管理器在 Visual Studio 2019 中不起作用!)。
这是代码:
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);
}
}
我将这个预填充的 SQLite 文件复制到我的应用程序中,位于主项目的根目录下。在此文件的属性中,我在“构建操作”中指示“嵌入式资源”。
程序第一次运行时,会检查是否找到SQLite文件。如果找不到,我使用Dirk here给出的代码将文件复制到特殊文件夹“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 exemple 使用 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
消息:发送请求时出错。
我的代码不正确吗?
请帮助我,我想完成我的应用程序。非常感谢。
我终于成功地将我的 SQLite 数据库备份并恢复到 OneDrive。
它既简单又复杂。
如果您按照 Microsoft 在此处提供的 Graph 和 Azure 示例进行操作,这很简单:
https://docs.microsoft.com/en-us/graph/tutorials/xamarin?tutorial-step=1
而且它很复杂,因为这个例子没有解释如何将文件复制到 OneDrive。
这是我所做的:
我按照 Microsoft 的 step-by-step 示例将其应用于我的应用程序。
在 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");
}
在我的应用程序中一切正常。
我希望我能帮助那些仍在寻找解决这个问题的人。如果您想了解更多信息,请随时问我任何问题。
我的 Xamarin.forms 应用程序 (Android) 集成了一个 SQLite 数据库,由于我在此处找到的示例,我可以正确管理它:https://docs.microsoft.com/fr-fr/xamarin/get-started/quickstarts/database
我的第一个问题是:如何保存这个 notes.db3 文件(在 Onedrive 或 Google 驱动器上)。
我的第二个问题:如何为应用程序提供包含数据表的数据库。我在网上了解到,您需要将预填充的文件sqlite.db3复制到Resources文件夹,然后将这个带有代码的文件复制到application文件夹。
我搜索了很多,但找不到能够做到这一点的确切代码。 谢谢你帮助我,这将非常有用,因为关于这个主题的文档很少。
编辑: 这是第二个问题的答案:
- 当新用户第一次使用该程序 运行 时,我使用该程序用有用的数据填充表格。
- 我以编程方式将 SQLite 文件复制到可通过外部应用程序访问的文件夹中:Android Studio(Android Device Monitor 实用程序的文件管理器在 Visual Studio 2019 中不起作用!)。 这是代码:
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);
}
}
我将这个预填充的 SQLite 文件复制到我的应用程序中,位于主项目的根目录下。在此文件的属性中,我在“构建操作”中指示“嵌入式资源”。
程序第一次运行时,会检查是否找到SQLite文件。如果找不到,我使用Dirk here给出的代码将文件复制到特殊文件夹“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 exemple 使用 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 消息:发送请求时出错。
我的代码不正确吗? 请帮助我,我想完成我的应用程序。非常感谢。
我终于成功地将我的 SQLite 数据库备份并恢复到 OneDrive。 它既简单又复杂。 如果您按照 Microsoft 在此处提供的 Graph 和 Azure 示例进行操作,这很简单: https://docs.microsoft.com/en-us/graph/tutorials/xamarin?tutorial-step=1 而且它很复杂,因为这个例子没有解释如何将文件复制到 OneDrive。 这是我所做的: 我按照 Microsoft 的 step-by-step 示例将其应用于我的应用程序。
在 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");
}
在我的应用程序中一切正常。 我希望我能帮助那些仍在寻找解决这个问题的人。如果您想了解更多信息,请随时问我任何问题。