C#数据备份与还原,源码实例

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(fbd.SelectedPath))
            {
                this.txtBackup.Text = fbd.SelectedPath;
            }
        }

        private void btnBackup_Click(object sender, EventArgs e)
        {
            if (txtBackup.Text == "")
            {
                MessageBox.Show("请选择要备份的目录");
                return;
            }
            string backupData = txtBackup.Text +"\\"+ DateTime.Now.ToString("yyyyMMddHHmmss") + "Data.db";
            string sourcePath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\Data.db"; //源文件完整路径
            File.Copy(sourcePath, backupData,true);
            if (File.Exists(backupData))
            {
                MessageBox.Show("备份成功");
            }
            else
            {
                MessageBox.Show("备份失败");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.DefaultExt = "db";
            ofd.Filter = "数据库文件(*.db)|*.db";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(ofd.FileName))
            {
                this.txtReduction.Text = ofd.FileName;
            }
        }

        private void btnReduction_Click(object sender, EventArgs e)
        {
            if (txtReduction.Text == "")
            {
                MessageBox.Show("请选择要还原的文件");
                return;
            }
            string sourcePath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\Data.db"; //源文件完整路径
            File.Copy(txtReduction.Text, sourcePath, true);
            if (File.Exists(sourcePath))
            {
                MessageBox.Show("备份成功");
            }
            else
            {
                MessageBox.Show("备份失败");
            }
        }

评论