1.窗体设计:2个button(1个备份(BtnDataBackup),1个恢复(BtnDataRecovery)),1个label(labMsg);1个openFileDialog1(打开选择文件对话窗口);
2:代码
using System.IO;
private void BtnDataBackup_Click(object sender, EventArgs e) {//数据备份按钮 string dbFilePath = Application.StartupPath + @"dataorders.db"; string dbNewFilePath=Application.StartupPath + @"dataackuporders"+ DateTime.Now.ToString("yyyyMMddHHmmss") + ".db"; string dirPath=Application.StartupPath + @"dataackup"; try { if (!Directory.Exists(dirPath)) {//创建backup文件夹 Directory.CreateDirectory(dirPath); } File.Copy(dbFilePath, dbNewFilePath);//拷贝文件 if (File.Exists(dbNewFilePath)) { labMsg.Text="数据库文件备份成功,文件路径: " + dbNewFilePath; } } catch { labMsg.Text="数据备份失败,备份的同时,不要进行其他操作!"; } } private void BtnDataRecovery_Click(object sender, EventArgs e) {//数据恢复按钮 string backUpDir = Application.StartupPath + @"dataackup"; string dbFilePath = Application.StartupPath + @"dataorders.db"; //选择文件 openFileDialog1.Filter = "db文件|*.db";//筛选文件类型 openFileDialog1.InitialDirectory = backUpDir; if (openFileDialog1.ShowDialog() == DialogResult.OK) {//恢复[覆盖]文件 File.Copy(openFileDialog1.FileName, dbFilePath, true);//拷贝文件,存在则覆盖(也可以弹messagebox,让用户选择是否覆盖) if (File.GetLastWriteTime(openFileDialog1.FileName).ToString("yyyyMMddHHmmss") == File.GetLastWriteTime(dbFilePath).ToString("yyyyMMddHHmmss")) {//通过比较2个文件的修改日期,进行判断 labMsg.Text = "数据恢复成功。"; } else { labMsg.Text = "数据恢复失败,请手动拷贝文件进行恢复。"; } } openFileDialog1.Dispose(); }