如何使用winform创建和恢复数据库备份?

时间:2011-05-24 16:58:05

标签: c#

我正在制作一个应用程序,我想给一个按钮,在用户所需的位置创建数据库备份;就像我们在计算机上的任何目的地上保存任何文件和一个按钮来恢复整个数据库的备份。如何完成这项任务?

我正在通过此代码进行备份:

SqlCommand cmd = new SqlCommand(@"backup database StockDB to disk ='d:\StockDBBackUp1.bak' with init,stats=10", ConnectionClass.OpenConnection());  
cmd.ExecuteNonQuery(); 

现在,如果我提供文件夹名称d:\Backup\StockDBBackUp1.bak,那么它应该检查文件夹是否存在。如果没有,那么它应该创建文件夹并创建备份。

2 个答案:

答案 0 :(得分:2)

您可以使用System.IO函数来完成目录的创建:

if (!Directory.Exists(@"D:\Backup"))
    Directory.CreateDirectory(@"D:\Backup");

答案 1 :(得分:0)

    private void button11_Click(object sender, EventArgs e)
  {
            DateTime PD = new DateTime(DateTime.Today);
            saveFileDialog1.FileName = PD.ToString("yyyy-MM-dd");
            saveFileDialog1.Filter = " files|*.bak;*.BAK";
            saveFileDialog1.InitialDirectory = "d:";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string path = string.Empty;
                    path = saveFileDialog1.FileName;

                    path = path.Replace("\\", "//");
                    bool bBackUpStatus = true;
                    Cursor.Current = Cursors.WaitCursor;
                    if (System.IO.File.Exists(path))
                    {
                        if (MessageBox.Show(@"do you want a new one?", "the file is existing", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            System.IO.File.Delete(path);
                        }
                        else
                            bBackUpStatus = false;
                    }
                    if (bBackUpStatus)
                    {
                        //Connect to DB
                        SqlConnection Conn = new SqlConnection("Server=(local); Data Source=LocalHost; DataBase=Exchange; UID=sa; Pwd=sql");
                        //string con = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirector  y|\SRVCARD.mdf;Integrated Security=True;User Instance=True";
                        if (Conn.State.ToString() == "Open")
                        {
                            Conn.Close();
                        }
                        Conn.Open();
                        SqlCommand command = new SqlCommand(@"backup database Exchange To Disk='" + path + "' with stats=10", Conn);
                        command.ExecuteNonQuery();
                        Conn.Close();
                        MessageBox.Show("Backup successfully", "Backup", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("please change the path");
                    //MessageBox.Show(ex.ToString());
                }
            }