在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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 + @"\data\orders.db"; string dbNewFilePath=Application.StartupPath + @"\data\backup\orders"+ DateTime.Now.ToString("yyyyMMddHHmmss") + ".db"; string dirPath=Application.StartupPath + @"\data\backup"; 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 + @"\data\backup"; string dbFilePath = Application.StartupPath + @"\data\orders.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(); }
|
请发表评论