我已经为我的应用程序创建了备份和恢复过程。运行备份时,它将在与数据库相同的目录中创建 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");
我的问题是,当我有打开连接的代码时,例如,当我在执行恢复后打开系统设置页面时,我收到错误:
"Could not open database file: /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);
无法创建数据库并显示消息
"Could not open database file: /data/user/0/com.companyname.ACPlus_MobileEPOS/files/EPOSDatabase.db3"
看起来该文件不存在,因此没有正确提取,但如果是这样的话,为什么它不只是创建一个新数据库,而不是尝试打开它?
最佳答案
需要重新检查提取逻辑。
Extracts all the files in the specified zip archive to a directory on the file system.
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");
}
关于c# - 恢复数据库时提取 Zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52624273/