Backup and Restore Sql Server database in C#
This tutorial explains how to create a Sql Server Backup file in C# and also how to restore the
database. We use a Backup file and restore database when our database becomes
corrupted or crashes. So let's have a pratical example of how to create it in C#, this example is
developed in Visual Studio 2010.
First, we create this Windows Form and we declare the connectionString of the database.
We start by the Backup, in BrowseButton click event we add this code:
In BackupButton click event we add this code:
Then, let's handle Restore database. In BrowseButton click event we add this code:
Finally, in RestoreButton click event we put this code:
Fore more explanation, watch this video:
database. We use a Backup file and restore database when our database becomes
corrupted or crashes. So let's have a pratical example of how to create it in C#, this example is
developed in Visual Studio 2010.
First, we create this Windows Form and we declare the connectionString of the database.
SqlConnection con = new SqlConnection(WindowsFormsApplication11.Properties.Settings.Default.database1ConnectionString);
We start by the Backup, in BrowseButton click event we add this code:
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.SelectedPath;
BackupButton.Enabled = true;
}
}
In BackupButton click event we add this code:
private void BackupButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
try
{
if(textBox1.Text==string.Empty)
{
MessageBox.Show("please enter backup file location");
}
else
{
string cmd = "BACKUP DATABASE [" + database + "] 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("database backup done successefully");
BackupButton.Enabled = false;
}
}
}
catch
{
}
}
Then, let's handle Restore database. In BrowseButton click event we add this code:
private void Browsebutton2_Click(object sender, EventArgs e)
{
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;
restoreButton.Enabled = true;
}
}
Finally, in RestoreButton click event we put this code:
private void restoreButton_Click(object sender, EventArgs e)
{
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());
}
}
Fore more explanation, watch this video:
Backup and Restore Sql Server database in C#
Reviewed by Bloggeur DZ
on
11:58
Rating:
en la cadena de conexion, la parte de database1ConnectionString a que hace referencia?? le e puesto el nombre de la base de datos y me marca error
RépondreSupprimerVery nice.
RépondreSupprimerThanks...#aspmantra.com
RépondreSupprimer"\\" + "database" + "-" what is this in code which location...this database word give error ..please help me
RépondreSupprimerThis article more help me to understand about backup and restore sql server database
RépondreSupprimerconvert foxpro code to sql
convert visual foxpro database to sql
foxpro database to sql server
import dbf file into sql server
Great work bro. Complete yet precise. Keep it up the great work. Thanks!
RépondreSupprimerhow to take back up sql server data base with different Name Like DataBase_Restore and Restore with new Name
RépondreSupprimerThanks for sharing this useful article. Looking for a best Database Backup and Restore Services in usa. We provide this service for an affordable price. Database Backup and Restore Services in usa
RépondreSupprimerFailed to update database "msdb" because the database is read-only.
RépondreSupprimerCould not insert a backup or restore history/detail record in the msdb database. This may indicate a problem with the msdb database. The backup/restore operation was still successful.
Thank you for an excellent article. You made an interesting article.
RépondreSupprimerSQL Azure Online Training
Azure SQL Training
SQL Azure Training
hii its helpfull but i am not able to backup same database witch is in the project....help me
RépondreSupprimerRecovering the data base
RépondreSupprimerAt Genex DBS data loss is only temporary and we prove it every day with the highest data recovery success rate in the industry. Our volume of recovered data speaks for itself.
For over 17 years, Data Storage Solutions has performed professional data recovery on every kind of storage device including Desktop hard drive data recovery, Laptop hard drives data recovery, External / USB hard disc Data Recovery / Hard Disc Recovery, Server and RAID arrays data recovery, NAS, SAN, DAS, SSD, Encryption storage devices data recovery, Database & File Recovery, CCTV Data Recovery, Flash Card Data Recovery. and enterprise-level devices like RAIDs. We have proprietary tools to handle every kind of data loss situation on any server including physical and mechanical failure, backup failure, water and fire damage, data corruption, file deletion, head crash, system failure, and more. We conduct all our data recoveries using software and solutions that won’t further damage your device.Genexdbs Database