C# 使用SaveFileDialog备份SQLite数据库?
我遵循此处提供的指导: 它的工作原理与我预期的一样,但我希望将BackupDb.db文件传递到SaveFileDialog中,这样用户就可以将文件保存在applications文件夹之外,最好是保存在外部驱动器上。我就是搞不懂 这就是我到目前为止所做的:C# 使用SaveFileDialog备份SQLite数据库?,c#,.net,wpf,sqlite,C#,.net,Wpf,Sqlite,我遵循此处提供的指导: 它的工作原理与我预期的一样,但我希望将BackupDb.db文件传递到SaveFileDialog中,这样用户就可以将文件保存在applications文件夹之外,最好是保存在外部驱动器上。我就是搞不懂 这就是我到目前为止所做的: private void btn_backup_db_Click(object sender, RoutedEventArgs e) { var ofd1 = new Microsoft.Win32.SaveFileD
private void btn_backup_db_Click(object sender, RoutedEventArgs e)
{
var ofd1 = new Microsoft.Win32.SaveFileDialog();
using (var source = new SQLiteConnection("Data Source=database.db; Version=3;"))
using (var destination = new SQLiteConnection("Data Source=BackupDb.db; Version=3;"))
{
source.Open();
destination.Open();
source.BackupDatabase(destination, "main", "main", -1, null, 0);
//Microsoft.Win32.SaveFileDialog saveFileDialog;
ofd1.ShowDialog();
}
我知道我错过了一步,但我不知道是哪一步。我将ofd1变量定义为打开SaveFileDialog,并告诉它使用of1.ShowDialog()打开;但是我不能将“main”或“destination”传递到SaveFileDialog,因为SQLite没有显示对话框的定义
我正在尝试使用以下命令获取文件的路径:
private string MyDirectory()
{
return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}
但是我得到一个异常,声明我没有对目录的读取权限
于是,我开始尝试这个,但我不知道如何正确使用它。它指向基本目录,但在bin\debug中找不到任何内容:
var dir = AppDomain.CurrentDomain.BaseDirectory;
这就是答案,我包括了从btn_备份到db_点击的所有内容:
private void btn_backup_db_Click(object sender, RoutedEventArgs e)
{
var ofd1 = new Microsoft.Win32.SaveFileDialog();
ofd1.Filter = "Database Files (*.db)|*.db";
ofd1.FileName = "database";
// customize file dialog properties here
if (ofd1.ShowDialog() == true)
{
var path = Path.GetFullPath(ofd1.FileName);
var destinationCnx = "Data Source=" + path + "; Version=3;";
using (var source = new SQLiteConnection("Data Source=database.db; Version=3;"))
using (var destination = new SQLiteConnection(destinationCnx))
{
source.Open();
destination.Open();
source.BackupDatabase(destination, "main", "main", -1, null, 0);
}
}
else
{
MessageBox.Show("Error");
}
}
非常感谢大家 SaveFileDialog类只是一个实用工具,它允许用户选择要保存文件的位置(以路径的形式) 总之,在使用sqlite执行任何操作之前,需要显示文件对话框。获得路径后,需要构建后连接字符串
var ofd1 = new SaveFileDialog();
// customize file dialog properties here
if (ofd1.ShowDialog() == true)
{
var path = Path.GetFullPath(ofd1.FileName);
var destinationCnx = "Data Source=" + path + "; Version=3;"
// do sqlite stuff here
}
你试过什么?您遇到了什么问题?调用SaveFileDialog,获取所选路径。然后从上一步创建备份SQLiteConnection连接字符串。@FrankerZ抱歉,更新了帖子。@ShamusLocke您甚至没有用ofd1做任何事情。显示对话框后,为什么不获取所述文件的位置,并对其进行处理?@FrankerZ'私有字符串MyDirectory(){return Path.GetDirectoryName(Assembly.getexecutinggassembly().location);}'我正试图使用此,但是我得到了一个异常,说我没有读取权限。我仍然没有得到一个文件,当我把我的SQLite代码放在if/then中时,我得到了“空语句”和无效的表达式term。你不会得到一个文件,只有一个文件路径。您不需要更多您是否将
SQLiteConnection(“数据源=BackupDb.db;版本=3;”)替换为SQLiteConnection(destinationCnx)
?哇,谢谢。这起作用了。我将用你的答案更新我的问题。我很感激。你能在回答中解释一下为什么这个方法有效,为什么我尝试的另外两种方法无效吗?