如何在C#窗口应用程序中创建备份和还原数据库 [英] How create Backup and Restore database in c# window application

查看:51
本文介绍了如何在C#窗口应用程序中创建备份和还原数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的代码中有问题,无法正确调试,但无法创建备份和还原
当我们单击备份"按钮时,计算机将重新启动,而不在目标文件夹plz中创建备份文件.

i have a problem in below code debug correctely but not create backup and restore
when we click on backup button then computer restart and not create backup files in destination folder plz help me..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Crime_System
{
    public partial class Backup_files : Form
    {
         public int controller = 0;
         public static Backup_files Bup;
         public Backup_files()
    {
            InitializeComponent();
        }
          
           public void restart(string msg)
         {
             if (controller == 0)
             {
                 if (Get_MSG_PAID(msg) == "yes")
                 {

                     FileStream fs = File.OpenWrite("backup.txt");
                     string s = "backup";

                     byte[] data = new byte[s.Length];
                     data = Encoding.ASCII.GetBytes(s);
                     fs.Write(data, 0, s.Length);
                     fs.Close();
                     System.Diagnostics.Process.Start("ShutDown", "/r");
                 }
             }
         }
         public string Get_MSG_PAID(string message)
         {
             // string message = "Are you sure to save ";
             string caption = "Back Up Confirmation.......";
             MessageBoxButtons buttons = MessageBoxButtons.YesNo;
             MessageBoxIcon icon = MessageBoxIcon.Question;
             //   buttons = MessageBoxButtons.OK;
             DialogResult result;


             // Displays the MessageBox.

             result = MessageBox.Show(message, caption, buttons, icon);

             //  System.Windows.Forms.DialogResult..Abort;

             if (result == System.Windows.Forms.DialogResult.Yes)
             {
                 return "yes";
             }
             else
             {
                 return "no";
             }
         }

         public static void Get_Control()
         {
             Bup = new Backup_files();
             Bup.ShowDialog();
         }
         public void ManualFileRestoration(string target)
         {
             try
             {
                 string path = "";
                 string path2 = "";
                 //FileStream fs = File.OpenWrite("dirinfo.txt");
                 // StreamWriter sfr = new StreamWriter(fs);
                 string subpath = @"c:\users\khan\documents\visual studio 2010\Projects\Crime System\Crime System\Database1.mdf";
                 string subpath2 = @"C:\Users\khan\Documents\Visual Studio 2010\Projects\Crime System\Crime System\Database1_log.ldf";
                 string sh = Directory.GetDirectoryRoot("dirinfo.txt");
                 path = sh + subpath;
                 path2 = sh + subpath2;
                 File.Copy(target + "Database1.mdf", path, true);
                 File.Copy(target + "Database1_log.ldf", path2, true);
                 MessageBox.Show("Back up successfully Restored");
             }
             catch (Exception ee)
             {
                 MessageBox.Show(ee.GetBaseException().ToString());
             }
         }

        private void button2_Click(object sender, EventArgs e)
        {
            if (controller != 0)
            {
                try
                {
                    if (!Directory.Exists(label1.Text))
                    {
                        MessageBox.Show("No Directory is exist");
                        return;
                    }
                    string path = "";
                    string path2 = "";
                    //FileStream fs = File.OpenWrite("dirinfo.txt");
                    // StreamWriter sfr = new StreamWriter(fs);
                    string subpath = @"c:\users\khan\documents\visual studio 2010\Projects\Crime System\Crime System\Database1.mdf";
                    string subpath2 = @"C:\Users\khan\Documents\Visual Studio 2010\Projects\Crime System\Crime System\Database1_log.ldf";
                    string sh = Directory.GetDirectoryRoot("dirinfo.txt");
                    path = sh + subpath;
                    path2 = sh + subpath2;

                    File.Copy(path, label1.Text + "Database1.mdf", true);
                    File.Copy(path2, label1.Text + "Database1_log.ldf", true);
                    MessageBox.Show("Successfuly Created Database Back Up");
                }
                catch (Exception ee)
                {
                    MessageBox.Show("ERROR" + ee.GetBaseException().ToString());
                }
            }
            else
                restart("you must have to restart computer to craate back up \n press ok to restart");
       
        }

        private void button3_Click_1(object sender, EventArgs e)
        {

            if (controller == 0)
            {
                this.Hide();
            }
            else
            {
                access obj = new access();
                //obj.Show();
                this.Hide();
            }
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            try
            {
                folderBrowserDialog1.ShowDialog().ToString();
                string s = folderBrowserDialog1.SelectedPath;
                string target = s + @"\";

                if (!File.Exists(target + "Database1.mdf"))
                {
                    MessageBox.Show("No data base file found");
                    return;
                }
                else if (!File.Exists(target + "Database1_log.ldf"))
                {
                    MessageBox.Show("No data base file found");
                    return;
                }
                label2.Text = target;

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.GetBaseException().ToString());
            }
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            Hashtable ht = new Hashtable();
            FileStream sfs = new FileStream("temp.xml", FileMode.Open, FileAccess.Read);

            Hashtable h = new Hashtable();
            BinaryFormatter formatter = new BinaryFormatter();
            h = (Hashtable)formatter.Deserialize(sfs);
            string status = Convert.ToString(h["admin"]);
            sfs.Close();
            if (status == "admin")
            {
                if (controller != 0)
                {
                    ManualFileRestoration(label2.Text);
                }
                else
                    restart("you must have to restart computer to restore back up \n press ok to restart");
                      }
            else
            {
                MessageBox.Show("Your are unable to perform this operatoin");

            }
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            if (controller == 0)
            {
                this.Hide();
            }
            else
            {
                access obj = new access();
                //obj.Show();
                this.Hide();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                folderBrowserDialog1.ShowDialog().ToString();
                string s = folderBrowserDialog1.SelectedPath;
                string target = s + @"\";
                label1.Text = target;
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.GetBaseException().ToString());
            }
        }
 
    }
}



请帮助我任何身体...指导我



plz help me any body...guide me

推荐答案

尝试一下:
Try this:
private void DatabaseBackup()
        {
            string strDate = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');
            string[] strTime = DateTime.Now.TimeOfDay.ToString().Split(':');
            string strDateTime = strDate + " " + strTime[0].PadLeft(2, '0') + strTime[1].PadLeft(2, '0');
            try
            {
                string backupPath = txtBackupLocation.Text.Trim() + "\\" + strDateTime + ".bak";
                int retVal = 0;
                DatabaseBackup(backupPath);
                if (retVal != 0)
                {
                    btnBackupDatabase.Enabled = false;
                    lblBackupStatus.Text = "Database backup successful.";
                    MessageBox.Show("Backup of database completed successfully." + Environment.NewLine + backupPath, Program.MESSAGEBOXTITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    btnClose.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error [Database Backup]: " + Environment.NewLine + ex.Message, Program.MESSAGEBOXTITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblBackupStatus.Text = "Database backup failed.";
            }
        }





public int DatabaseBackup(string backupPath)
        {
            int retVal = 0;

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand();
            
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = @"Backup Database To Disk = '" + backupPath + "' WITH INIT";
            try
            {
                conn.Open();
                cmd.Connection = conn;
                retVal = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
            finally
            {
                conn.Close();
            }

            return retVal;
        }


一旦看到,他们给了我们全部代码

http://technico.qnownow.com /2012/04/02/backup-and-restore-sql-server-database-programmatically-in-c/ [
once see this they gave us total code

http://technico.qnownow.com/2012/04/02/backup-and-restore-sql-server-database-programmatically-in-c/[^]


//用于获取我们要从中还原的数据库的列表...


con =新的SqlConnection(@数据源=" +服务器名+;初始目录= master;用户ID =" +用户+;密码=" +密码+");
con.Open();
cmd =新的SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="exec sp_databases";
dr = cmd.ExecuteReader();
while(dr.Read())
{
comboBox1.Items.Add(dr.GetString(0));
}






con =新的SqlConnection(@"Data Source =" + serverName +; Initial Catalog = master; User ID =" + user +; Password =" + password +");

数据库= comboBox1.SelectedItem.ToString();//此处选择数据库

试试
{
fbd = new FolderBrowserDialog();//用于保存数据库备份
结果= fbd.ShowDialog();
System.IO.DirectoryInfo dir =新的System.IO.DirectoryInfo(fbd.SelectedPath);
path = dir.ToString();//文件夹位置
con.Open();
//查询要备份的数据库
cmd = new SqlCommand(备份数据库测试到磁盘=""+路径+" \\"+数据库+ DateTime.Now.ToString(" ddMMMyyyy)+" .Bak",con);
cmd.ExecuteNonQuery();
//关闭连接
con.Close();
MessageBox.Show(数据库备份成功完成");


我认为这对您有帮助……
//use for list of database from which we want to restore…


con = new SqlConnection(@"Data Source=" + servername + ";Initial Catalog=master;User ID=" + user + ";Password=" + password + "");
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "exec sp_databases";
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr.GetString(0));
}






con = new SqlConnection(@"Data Source=" + serverName + ";Initial Catalog=master;User ID=" + user + ";Password=" + password + "");

Database = comboBox1.SelectedItem.ToString();//here we select database

try
{
fbd = new FolderBrowserDialog();//use for save backup of database
result = fbd.ShowDialog();
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(fbd.SelectedPath);
path = dir.ToString();//folder location
con.Open();
//query to take backup database
cmd = new SqlCommand("backup database test to disk=''" + path + "\\" + databse + DateTime.Now.ToString("ddMMMyyyy") + ".Bak''", con);
cmd.ExecuteNonQuery();
//Close connection
con.Close();
MessageBox.Show("Backup of database is Done successfully");


I think this will help you……


这篇关于如何在C#窗口应用程序中创建备份和还原数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆