C#WinForm程序常用函数设计

本文介绍了如何使用C#实现数据库的备份与还原功能,包括窗口关闭提示、数据库备份及还原的具体实现步骤。备份过程涉及从SQL Server中分离数据库并复制文件至指定位置,而还原则需先分离现有数据库再替换为备份文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:窗口关闭提示函数

 private void Fmain_FormClosing_1(object sender, FormClosingEventArgs e)
        {
            DialogResult rst = MessageBox.Show(this,"您真的要退出吗?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
            switch (rst)
            {
                case DialogResult.Yes:
                    Application.ExitThread();
                    Application.Exit();
                    break;
                case DialogResult.No:
                    e.Cancel=true;
                    break;

            }
        }

二:数据库备份函数;

  private void 数据库备份ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
            folderBrowserDialog1.Description =
                "请选择将学籍数据(OpratateDB.mdf)备份到哪个位置:";
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            folderBrowserDialog1.ShowNewFolderButton = true;
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                //先将数据库从SQL Server 2005中分离出来,然后再备份
                try
                {
                    DetatchStudentsDatabase();
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message, "分离数据库失败",
                        MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }
                //获取目标文件夹位置
                string targetPath = folderBrowserDialog1.SelectedPath;
                //获取源文件夹位置
                string sourcePath = Program.dbPath;
                if (targetPath.EndsWith(@"\") == false)
                {
                    targetPath += @"\";
                }
                string source1 = sourcePath + @"\OpratateDB.mdf";
                string source2 = sourcePath + @"\OpratateDB_log.ldf";
                string target1 = targetPath + @"\OpratateDB.mdf";
                string target2 = targetPath + @"\OpratateDB_log.ldf";
                if (System.IO.File.Exists(target1))
                {
                    DialogResult overWriteResult = MessageBox.Show(
                        "目标位置已经存在数据库,覆盖吗?", "",
                        MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    if (overWriteResult != DialogResult.Yes)
                    {
                        MessageBox.Show("未进行备份,请按确定返回");
                        return;
                    }
                }
                try
                {
                    //如果目标文件已经存在,则直接覆盖
                    File.Copy(source1, target1, true);
                    File.Copy(source2, target2, true);
                    MessageBox.Show("备份成功", "恭喜",
                        MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message, "备份失败");
                }
            }
        }

   public void DetatchStudentsDatabase()
        {
            //鼠标指针呈现等待状态
            Cursor.Current = Cursors.WaitCursor;
            SqlConnection conn =
                new SqlConnection(coperaterDB.ConnString);
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                conn.Open();
                cmd.CommandText = "use master";
                cmd.ExecuteNonQuery();
                cmd.CommandText = string.Format("EXEC sp_detach_db @dbname = N'{0}", Program.dbPath + "OpratateDB.mdf'");
                cmd.ExecuteNonQuery();
            }
            catch
            {
                //重新抛出捕获的异常
                throw;
            }
            finally
            {
                conn.Close();
            }
            Cursor.Current = Cursors.Default;
        }

三:数据库还原函数

 private void 数据库还原ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            //设置筛选字符串
            openFileDialog1.Filter = "OperatateDB.mdf|*.mdf|所有文件(*.*)|*.*";
            openFileDialog1.Title = "还原数据库";
            //设置初始目录
            openFileDialog1.InitialDirectory = @"C:\";
            if (openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string fileName = openFileDialog1.FileName;
            if (fileName.EndsWith("OperatateDB.mdf") == true)
            {
                MessageBox.Show("选择的文件不是要恢复的数据库。", "恢复失败");
                return;
            }
            string sourcePath = fileName.Substring(0, fileName.LastIndexOf("OpratateDB.mdf"));
            string targetPath = Program.dbPath;
            try
            {
                DetatchStudentsDatabase();
                File.Copy(fileName, targetPath + "OpratateDB.mdf", true);
                File.Copy(sourcePath + "OpratateDB_log.ldf", targetPath + "OpratateDB_log.ldf", true);
                MessageBox.Show("恢复成功。");
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "恢复失败");
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值