【发布时间】:2013-06-23 09:41:11
【问题描述】:
我有这段代码在 C# 中使用 MS Access 作为其数据库进行备份和恢复。我完成了 zip 格式的备份,现在我想恢复 Zipped 文件。任何帮助都感激不尽。
public void BackupDatabase(string dateToday)
{
string dbFileName = "dbCPS.accdb";
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory , dbFileName);
string backTimeStamp = Path.GetFileNameWithoutExtension(dbFileName) + "_" + dateToday + ".zip";// +Path.GetExtension(dbFileName);
string destFileName = backTimeStamp;// +dbFileName;
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
string PathtobackUp = fbd.SelectedPath.ToString();
destFileName = Path.Combine(PathtobackUp, destFileName);
//File.Copy(CurrentDatabasePath, destFileName, true);
using (var zip = new ZipFile())
{
zip.AddFile(dbFileName);
zip.Save(destFileName);
}
MessageBox.Show("Backup successful! ");
}
}
private void backupToolStripMenuItem1_Click(object sender, EventArgs e)
{
BackupDatabase(DateTime.Now.ToString("ddMMMyyyy_HH.mm"));
}
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string pathBackup = restoreFile;
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
File.Copy(pathBackup, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
}
private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
openFileDialogBackUp.FileName = "dbCPS";
openFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + @"Sauvegardes";
if (openFileDialogBackUp.ShowDialog() == DialogResult.OK)
RestoreDatabase(openFileDialogBackUp.FileName);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
此代码提取压缩文件,但我不知道如何同时进行还原。
using (ZipFile zip = ZipFile.Read(restoreFile))
{
zip.ExtractAll(CurrentDatabasePath);
}
【问题讨论】:
-
您是否试图覆盖您的程序使用的开放数据库?或者只是找到正确的目标路径并将提取的文件覆盖前一个的问题?
-
@Steve 是的,我正在尝试覆盖打开的数据库。因为它的功能是恢复。
-
如果我要恢复 .accdb 文件,代码可以正常工作,但是当我恢复 zip 文件时,出现错误。我认为这意味着我需要先提取才能使用此代码“File.Copy(pathBackup, CurrentDatabasePath, true);”。我使用此代码时的错误是代码“使用(ZipFile zip = ZipFile.Read(restoreFile)){ zip.ExtractAll(CurrentDatabasePath); }”是文件已打开,所以我无法覆盖?
-
您使用什么库或参考来使用 ZipFile 函数?我在任何地方都找不到这个。
-
@Meta 你找到了吗?它的 Ionic.Zip。抱歉回复晚了。
标签: c# winforms extract restore zipfile