gpt4 book ai didi

c# - 将现有数据库(存储文件)复制到存储文件夹

转载 作者:行者123 更新时间:2023-11-30 12:09:37 25 4
gpt4 key购买 nike

在我的 Windows 应用商店应用程序中,我想将现有数据库复制到存储文件夹。
我的数据库放在项目的主文件夹中。

为了将数据表复制到存储文件夹,我使用以下代码(link to article):

 StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("people.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);

在 VS 中的 Debug模式下一切正常。
但是,如果我使用 Release模式或只是停止调试并从 Windows 打开我的应用程序 - 它不起作用。
也没有抛出异常。尝试调用 CopyAsync 时,应用会卡住。
我敢肯定,我的 databaseFile!=null 也处于 Release模式。

我也试过这样获取文件:

var uri = new Uri("ms-appx:///people.sqlite");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

但这并没有解决我的问题。

问题:将现有数据库复制到存储文件夹的正确方法是什么?

更新:

谢谢你们的回答,但我无法解决我的问题(

我使用 CaliburnMicro 来实现 MVVM。

在页面 Loaded 我调用时在我的 View 模型上:

private async Task PrepareDatabase()
{
bool isDatabaseExisting;
var storageFolder = ApplicationData.Current.LocalFolder; ;
try
{
await storageFolder.GetFileAsync("database_name.sqlite");
isDatabaseExisting = true;
}
catch
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("database_name.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
}

我的数据库:
名称 - database_name.sqlite;
构建操作 - 内容;
复制到输出目录 - 始终复制;

当我从 visual studio 启动应用程序时 - 一切正常。
然后我停止调试,并从 Windows 运行应用程序 - 当它尝试打开此页面时它卡住了。

最佳答案

在“Build Action”属性下,您会找到一个名为“Copy To Output Directory”的属性。确保将其设置为“始终复制”

编辑:

还有另一种方法可以在您的项目中包含文件,即嵌入式资源。

在属性中,将 Build Action 设置为“Embedded Resource”。

using System.Reflection;


public MainPage()
{
this.InitializeComponent();
Assembly asm = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = asm.GetManifestResourceStream("YourNamespace.filename.extension");


ConvertToFileAndCopyToLocalDirectory(stream);
}

关于c# - 将现有数据库(存储文件)复制到存储文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21045501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com