我已经为我的应用程序创建了备份和还原过程。运行备份时,它将在与数据库相同的目录中创建SQLite数据库的.zip文件。
还原数据库时,它将重命名数据库,将其从EPOSDatabase.db3
更改为tempEPOS.db3
然后,在删除重命名的临时数据库之前,它将选择的文件提取并提取到名称为EPOSDatabase.db3
的相同位置。
string dbPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if (File.Exists(dbPath + "/tempEPOS.db3"))
{
File.Delete(dbPath + "/tempEPOS.db3");
};
File.Move(dbPath + "/EPOSDatabase.db3", dbPath + "/tempEPOS.db3");
ZipFile.ExtractToDirectory(dbPath + "/" + fileToRestore, dbPath + "/EPOSDatabase.db3");
File.Delete(dbPath + "/tempEPOS.db3");
我的问题是,当我有了打开连接的代码时,例如在执行还原后打开系统设置页面时,出现错误:
“无法打开数据库文件:/data/user/0/com.companyname.ACPlus_MobileEPOS/files/EPOSDatabase.db3(CannotOpen)”
作为进一步的调试测试,我将以下代码添加到应用程序的启动中:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
foreach (var file in Directory.GetFiles(path))
{
string strFile = Convert.ToString(file);
}
public readonly string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "EPOSDatabase.db3");
var db = new SQLiteConnection(dbPath);
db.CreateTable<Category>();
db.CreateTable<SystemSettings>();
db.Close();
在foreach循环中,它仅找到了我尝试从中还原的原始.zip文件。
然后当它到达一行时
var db = new SQLiteConnection(dbPath);
它无法使用消息
创建数据库“无法打开数据库文件:/data/user/0/com.companyname.ACPlus_MobileEPOS/files/EPOSDatabase.db3”
文件似乎不存在,因此没有正确提取,但是如果是这种情况,那么为什么它不只是创建一个新数据库,而不是尝试打开它?
答案 0 :(得分:2)
提取逻辑需要重新检查。
将指定的zip存档中的所有文件提取到文件系统上的目录中。
public static void ExtractToDirectory (string sourceArchiveFileName, string destinationDirectoryName);
使用原始代码
ZipFile.ExtractToDirectory(dbPath + "/" + fileToRestore, dbPath + "/EPOSDatabase.db3");
zip文件的内容正在提取到名为{path}/EPOSDatabase.db3/
的目录。
如果目标只是从存档中提取到目录,则仅需要目录位置。
ZipFile.ExtractToDirectory(dbPath + "/" + fileToRestore, dbPath);
另外,在删除旧文件之前,应进行检查以确保所需的文件在还原后确实存在。
//... extraction code omitted for brevity
if (!File.Exists(dbPath + "/EPOSDatabase.db3")) {
//...either throw error or alert that database is not present
//...could consider return old file back to original sate (optional)
} else {
File.Delete(dbPath + "/tempEPOS.db3");
}