SQL Server Backup/Restore Through SQLDMO and C#

http://www.csharphelp.com/archives2/archive345.html
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
namespace SQLBackupRestore
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        // The application object for getting server list
        private SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
        //NameList variable for server name collection
        SQLDMO.NameList sqlServers=null;
        private System.Windows.Forms.LinkLabel linkLabel2;
        private System.Windows.Forms.TextBox txtPassword;
        private System.Windows.Forms.TextBox txtUser;
        private System.Windows.Forms.ComboBox cboServers;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Button btnSubmit;
        private System.Windows.Forms.RadioButton radioButton2;
        private System.Windows.Forms.RadioButton radioButton1;
        private System.Windows.Forms.TextBox txtFile;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.ComboBox cboDatabase;
        private System.Windows.Forms.Button btnFile;
        private System.Windows.Forms.OpenFileDialog openFileDialog1;
        private System.Windows.Forms.SaveFileDialog saveFileDialog1;
        private System.Windows.Forms.Label label5;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.linkLabel2 = new System.Windows.Forms.LinkLabel();
            this.txtPassword = new System.Windows.Forms.TextBox();
            this.txtUser = new System.Windows.Forms.TextBox();
            this.cboServers = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.label5 = new System.Windows.Forms.Label();
            this.btnFile = new System.Windows.Forms.Button();
            this.btnSubmit = new System.Windows.Forms.Button();
            this.radioButton2 = new System.Windows.Forms.RadioButton();
            this.radioButton1 = new System.Windows.Forms.RadioButton();
            this.txtFile = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.cboDatabase = new System.Windows.Forms.ComboBox();
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            //
            // linkLabel2
            //
            this.linkLabel2.Location = new System.Drawing.Point(176, 128);
            this.linkLabel2.Name = "linkLabel2";
            this.linkLabel2.Size = new System.Drawing.Size(80, 16);
            this.linkLabel2.TabIndex = 16;
            this.linkLabel2.TabStop = true;
            this.linkLabel2.Text = "Connect";
            this.linkLabel2.TextAlign = System.Drawing.ContentAlignment.TopRight;
            this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
            //
            // txtPassword
            //
            this.txtPassword.Location = new System.Drawing.Point(8, 104);
            this.txtPassword.Name = "txtPassword";
            this.txtPassword.Size = new System.Drawing.Size(248, 20);
            this.txtPassword.TabIndex = 13;
            this.txtPassword.Text = "";
            //
            // txtUser
            //
            this.txtUser.Location = new System.Drawing.Point(8, 64);
            this.txtUser.Name = "txtUser";
            this.txtUser.Size = new System.Drawing.Size(248, 20);
            this.txtUser.TabIndex = 12;
            this.txtUser.Text = "sa";
            //
            // cboServers
            //
            this.cboServers.Location = new System.Drawing.Point(8, 24);
            this.cboServers.Name = "cboServers";
            this.cboServers.Size = new System.Drawing.Size(248, 21);
            this.cboServers.TabIndex = 11;
            this.cboServers.SelectedIndexChanged += new System.EventHandler(this.cboServers_SelectedIndexChanged);
            //
            // label1
            //
            this.label1.Location = new System.Drawing.Point(8, 8);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(176, 16);
            this.label1.TabIndex = 17;
            this.label1.Text = "Server";
            //
            // label2
            //
            this.label2.Location = new System.Drawing.Point(8, 48);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(184, 16);
            this.label2.TabIndex = 18;
            this.label2.Text = "Login";
            //
            // label3
            //
            this.label3.Location = new System.Drawing.Point(8, 88);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(128, 16);
            this.label3.TabIndex = 19;
            this.label3.Text = "Password";
            //
            // groupBox1
            //
            this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                                    this.label5,
                                                                                    this.btnFile,
                                                                                    this.btnSubmit,
                                                                                    this.radioButton2,
                                                                                    this.radioButton1,
                                                                                    this.txtFile,
                                                                                    this.label4,
                                                                                    this.cboDatabase});
            this.groupBox1.Location = new System.Drawing.Point(8, 144);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(248, 168);
            this.groupBox1.TabIndex = 20;
            this.groupBox1.TabStop = false;
            //
            // label5
            //
            this.label5.Location = new System.Drawing.Point(8, 112);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(136, 48);
            this.label5.TabIndex = 31;
            this.label5.Text = "Type in a path on the remote server for a remote database, or choose for local da" +
                "tabase.";
            //
            // btnFile
            //
            this.btnFile.Location = new System.Drawing.Point(208, 88);
            this.btnFile.Name = "btnFile";
            this.btnFile.Size = new System.Drawing.Size(32, 20);
            this.btnFile.TabIndex = 30;
            this.btnFile.Text = "...";
            this.btnFile.Click += new System.EventHandler(this.btnFile_Click);
            //
            // btnSubmit
            //
            this.btnSubmit.Location = new System.Drawing.Point(152, 128);
            this.btnSubmit.Name = "btnSubmit";
            this.btnSubmit.Size = new System.Drawing.Size(88, 24);
            this.btnSubmit.TabIndex = 29;
            this.btnSubmit.Text = "Back-Up";
            this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
            //
            // radioButton2
            //
            this.radioButton2.Location = new System.Drawing.Point(112, 64);
            this.radioButton2.Name = "radioButton2";
            this.radioButton2.Size = new System.Drawing.Size(96, 16);
            this.radioButton2.TabIndex = 28;
            this.radioButton2.Text = "Restore From";
            this.radioButton2.CheckedChanged += new System.EventHandler(this.radioButton2_CheckedChanged);
            //
            // radioButton1
            //
            this.radioButton1.Checked = true;
            this.radioButton1.Location = new System.Drawing.Point(8, 64);
            this.radioButton1.Name = "radioButton1";
            this.radioButton1.Size = new System.Drawing.Size(120, 16);
            this.radioButton1.TabIndex = 27;
            this.radioButton1.TabStop = true;
            this.radioButton1.Text = "Back-up To";
            this.radioButton1.CheckedChanged += new System.EventHandler(this.radioButton1_CheckedChanged);
            //
            // txtFile
            //
            this.txtFile.BackColor = System.Drawing.SystemColors.Window;
            this.txtFile.Location = new System.Drawing.Point(8, 88);
            this.txtFile.Name = "txtFile";
            this.txtFile.Size = new System.Drawing.Size(200, 20);
            this.txtFile.TabIndex = 26;
            this.txtFile.Text = "c://NWIND.bak";
            //
            // label4
            //
            this.label4.Location = new System.Drawing.Point(8, 16);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(88, 16);
            this.label4.TabIndex = 25;
            this.label4.Text = "Databases";
            //
            // cboDatabase
            //
            this.cboDatabase.Location = new System.Drawing.Point(8, 32);
            this.cboDatabase.Name = "cboDatabase";
            this.cboDatabase.Size = new System.Drawing.Size(232, 21);
            this.cboDatabase.TabIndex = 24;
            this.cboDatabase.Text = "Northwind";
            //
            // saveFileDialog1
            //
            this.saveFileDialog1.FileName = "doc1";
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(266, 319);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.groupBox1,
                                                                          this.label3,
                                                                          this.label2,
                                                                          this.label1,
                                                                          this.linkLabel2,
                                                                          this.txtPassword,
                                                                          this.txtUser,
                                                                          this.cboServers});
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "SQL Back-Up and Restore";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.groupBox1.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            try
            {
                //get all available SQL Servers               
                sqlServers = sqlApp.ListAvailableSQLServers();
                for(int i=0;i<sqlServers.Count;i++)
                {
                    object srv = sqlServers.Item( i + 1);
                    if(srv != null)
                    {
                        this.cboServers.Items.Add(srv);                       
                    }
                }
                if(this.cboServers.Items.Count > 0)
                    this.cboServers.SelectedIndex = 0;
                else
                    this.cboServers.Text = "<No available SQL Servers>";

            }
            catch(Exception err)
            {
                MessageBox.Show(err.Message,"Error");
            }
        }

        //Get the databases and put into a combobox
        private void linkLabel2_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this.cboDatabase.Items.Clear();               
                SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();               
                srv.Connect(this.cboServers.SelectedItem.ToString(),this.txtUser.Text,this.txtPassword.Text);
                foreach(SQLDMO.Database db in srv.Databases)
                {
                    if(db.Name!=null)
                        this.cboDatabase.Items.Add(db.Name);
                }
                this.cboDatabase.Sorted = true;
                if(this.cboDatabase.Items.Count >0)
                {
                    //this.cboDatabase.SelectedIndex = 0;                   
                    this.groupBox1.Enabled = true;
                }
                else
                {
                    this.groupBox1.Enabled = false;                   
                    this.cboDatabase.Text = "<No databases found>";
                }
                this.Cursor = Cursors.Default;
            }
            catch(Exception err)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(err.Message,"Error");
            }
        }

        //Restore selected
        private void radioButton2_CheckedChanged(object sender, System.EventArgs e)
        {
            this.btnSubmit.Text = "Restore";

        }

        //Back-Up Selected
        private void radioButton1_CheckedChanged(object sender, System.EventArgs e)
        {
            this.btnSubmit.Text = "Back-Up";
        }

        //Server changed
        private void cboServers_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            this.cboDatabase.Items.Clear();           
            this.groupBox1.Enabled = false;
            //this.txtFile.Text = "";
           
        }

        // Open/Save File Dialogs
        private void btnFile_Click(object sender, System.EventArgs e)
        {
            if(this.radioButton1.Checked)
            {
                //backup
                this.saveFileDialog1.ShowDialog();
                if(this.saveFileDialog1.FileName != "")
                    this.txtFile.Text = this.saveFileDialog1.FileName;
            }
            else
            {
                //restore
                this.openFileDialog1.ShowDialog();
                if(this.openFileDialog1.FileName != "")
                        this.txtFile.Text = this.openFileDialog1.FileName;
            }
        }

        //perform the backup/restore
        private void btnSubmit_Click(object sender, System.EventArgs e)
        {
            if(this.radioButton1.Checked)
                BackUp();
            else
                Restore();
        }

        private void BackUp()
        {
            try
            {               
                this.Cursor = Cursors.WaitCursor;
                //create an instance of a server class
                SQLDMO._SQLServer srv = new SQLDMO.SQLServerClass();               
                //connect to the server
                srv.Connect(this.cboServers.Text,this.txtUser.Text,this.txtPassword.Text);
                //create a backup class instance
                SQLDMO.Backup bak = new SQLDMO.BackupClass();                       
                //set the backup device = files property ( easy way )
                bak.Devices = bak.Files;
                //set the files property to the File Name text box
                bak.Files = this.txtFile.Text;
                //set the database to the chosen database
                bak.Database = this.cboDatabase.Text;
                //perform the backup
                bak.SQLBackup(srv);
                MessageBox.Show("Database successfully backed up.", "Backup Successfull");
                this.Cursor = Cursors.Default;
            }
            catch(Exception err)
            {           
                this.Cursor = Cursors.Default;
                MessageBox.Show(err.Message,"Error");
            }
        }
        private void Restore()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                //create an instance of a server class
                SQLDMO._SQLServer srv = new SQLDMO.SQLServerClass();               
                //connect to the server
                srv.Connect(this.cboServers.Text,this.txtUser.Text,this.txtPassword.Text);
                //create a restore class instance
                SQLDMO.Restore res = new SQLDMO.RestoreClass();               
                //set the backup device = files property ( easy way )
                res.Devices = res.Files;
                //set the files property to the File Name text box
                res.Files = this.txtFile.Text;
                //set the database to the chosen database
                res.Database = this.cboDatabase.Text;
                // Restore the database
                res.ReplaceDatabase = true;               
                res.SQLRestore(srv);               
                MessageBox.Show("Database restored successfully.", "Restore Successfull");       
                this.Cursor = Cursors.Default;
            }
            catch(Exception err)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(err.Message,"Error");
            }
        }
    }
}

Recently I had a need to be able to backup and restore databases from c#. I referred to the SQLDMO object and found it to be quite simple. The sample code will show you a simple method for doing backup/restore of SQL Server databases on a local network. I say "simple" because there are more complex and detailed methods for performing these operations, such as when you are using a backup device that is not a file. You can use these methods quite easily as well, but for this article I will only use a file path to backup and restore to. To use the sample app, just open the project. It should fix the reference to the COM object for you, but if not, just reference it as you see below.

The sample project does a few things. First it gets a list of available SQL Servers on the network on the Form_Load event and populates a combobox with the choices. You enter a login name and a password (SQL Authentication) and click "Connect" to get a list of the databases on the server. Once you have done this you can type a file name in or select one from the dialog. Please keep in mind that if it is a remote server, the dialogs will only point to a local file location which may not exist remotely. The backups and restores work based on physical paths relative to the server the database resides on. For instance, if it is a remote server, and the file path is c:/backup/db.bak, but the directory c:/backup does not exist on the remote server, it will fail. Althought this is a very base example, it has been useful to me. Happy coding!!!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值