Backup and Restore in C# Windows Form Application
Read Also:
Programming SeekerzZ |
To create backup of database from C# application and then restore it again from C# application follow the steps.
First design a form like bellow:
Form Design for Backup and Restore |
Browse Button of Backup Option:
FolderBrowserDialog dlg=new FolderBrowserDialog();
if(dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.SelectedPath;
}
Backup Button Code:
string databse = con.Database.ToString();
try
{
if (textBox1.Text == string.Empty)
{
MessageBox.Show("Please Enter by Browseing Database Backup Location....!");
}else
{
string cmd = "BACKUP DATABASE [" + databse + "] TO DISK='" + textBox1.Text + "\\" + "database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";
using(SqlCommand command = new SqlCommand(cmd, con))
{
if(con.State != ConnectionState.Open)
{
con.Open();
}
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Databse Backup has been Successefully Created..!");
}
}
}catch(Exception ex)
{
MessageBox.Show("Error\n\n" + ex);
}
Restore button Browse code:
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "SQL SERVER database backup files|*.bak";
dlg.Title = "Database restore";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox2.Text = dlg.FileName;
}
Restore Button Code:
try
{
string database = con.Database.ToString();
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
string sqlStmt2 = string.Format("ALTER DATABASE [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE DATABASE [" + database + "] FROM DISK='" + textBox2.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER DATABASE [" + database + "] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("Database Restoration Done Successefully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}catch(Exception ex) { }
If you are facing any problem in that program contact me with your issue :
https://www.facebook.com/usman.siddique.7771
Post a Comment