Database Backup Using C#

This article shows how to take a database backup using C# code and create a Windows application that makes our work user-friendly for database backup. Usually we do database backup using the SQL Server.

SQL Server Management Objects (also known as SMO) allows us to access the objects of Microsoft SQL Server. SMO is a .NET library. All functions available in SQL Server Management Studio is available in SMO but SMO has more features than Management Studio. 

Step 1

Open Visual Studio and choose a Windows application template and provide a nice name for the project.

VisualSTudioOpen

Step 2

Design the form as in the following:

Step2MainFormDesin

As in the preceding design of the application, when we click the Connect to the Server button there is a window open that asks for the credentials for the SQL database.

Another button "Fetch Database" allows fetching of the entire database inside the server that displays the the listbox as in the left side of the list box.

Another and last button is the "Backup Location" button for choosing the destination folder for where we to save the backup file. 

Step 3

Design another Windows for login as in the following:

LoginWIndow

Step 4

Fetch all the databases inside the server.

FetchButtonClicked 

The following is the code for connecting to SQL Server and fetch the databases.
  1. serverName = textBox1.Text;    
  2. userName = textBox2.Text;    
  3. password = textBox3.Text;    
  4. string str = "Data Source=" + textBox1.Text + ";User ID=" + textBox2.Text + ";Password=" + textBox3.Text + "";    
  5. SqlConnection con = new SqlConnection(str);    
  6. try    
  7. {    
  8.     con.Open();    
  9.    // MessageBox.Show("connection gets established");    
  10.     SqlCommand cmd = new SqlCommand("SELECT  db.[name] as dbname FROM [master].[sys].[databases] db", con);    
  11.     SqlDataAdapter sda = new SqlDataAdapter(cmd);                
  12.       
  13.     sda.Fill(ds,"DatabaseName");    
  14.     con.Close();    
  15.     this.Close();     
  16. }    
  17. catch(Exception ex)    
  18. {    
  19.     MessageBox.Show(ex.Message);    
  20. }  

Step 5

Choose the destination folder for where to keep the backup file. 

DestinatationFolderChoosed

After choosing the destination folder, we need to select the database and destination folder for further operations.

SelectTheDatabaseAndDestinationFolder

Step 6

We will now add a reference for Database Backup.

We need to add the following two very important namespaces.

  1. using Microsoft.SqlServer.Management.Smo;  
  2. using Microsoft.SqlServer.Management.Common;  

Step 7

We will now implement the code for the Database Backup.

After hitting the "Start Manual Back Up" button:

  1. private void button3_Click(object sender, EventArgs e)    
  2. {    
  3.     try    
  4.     {    
  5.         if (DestPath == "" || DbName == "")    
  6.         {    
  7.             MessageBox.Show("Try to select Database and Destination Folder !");    
  8.         }    
  9.         else    
  10.         {    
  11.             string databaseName = DbName;//dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString();    
  12.   
  13.             //Define a Backup object variable.    
  14.             Backup sqlBackup = new Backup();    
  15.   
  16.             ////Specify the type of backup, the description, the name, and the database to be backed up.    
  17.             sqlBackup.Action = BackupActionType.Database;    
  18.             sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" + DateTime.Now.ToShortDateString();    
  19.             sqlBackup.BackupSetName = "FullBackUp";    
  20.             sqlBackup.Database = databaseName;    
  21.   
  22.             ////Declare a BackupDeviceItem    
  23.             string destinationPath = DestPath;    
  24.             string backupfileName = DbName +".bak";    
  25.             BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + "\\" + backupfileName, DeviceType.File);    
  26.             ////Define Server connection    
  27.   
  28.             //ServerConnection connection = new ServerConnection(frm.serverName, frm.userName, frm.password);    
  29.             ServerConnection connection = new ServerConnection(Form1.serverName, Form1.userName, Form1.password);    
  30.             ////To Avoid TimeOut Exception    
  31.             Server sqlServer = new Server(connection);    
  32.             sqlServer.ConnectionContext.StatementTimeout = 60 * 60;    
  33.             Database db = sqlServer.Databases[databaseName];    
  34.   
  35.             sqlBackup.Initialize = true;    
  36.             sqlBackup.Checksum = true;    
  37.             sqlBackup.ContinueAfterError = true;    
  38.   
  39.             ////Add the device to the Backup object.    
  40.             sqlBackup.Devices.Add(deviceItem);    
  41.             ////Set the Incremental property to False to specify that this is a full database backup.    
  42.             sqlBackup.Incremental = false;    
  43.   
  44.             sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);    
  45.             ////Specify that the log must be truncated after the backup is complete.    
  46.             sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;    
  47.   
  48.             sqlBackup.FormatMedia = false;    
  49.             ////Run SqlBackup to perform the full database backup on the instance of SQL Server.    
  50.             sqlBackup.SqlBackup(sqlServer);    
  51.             ////Remove the backup device from the Backup object.    
  52.             sqlBackup.Devices.Remove(deviceItem);    
  53.             toolStripStatusLabel1.Text = "Successful backup is created!";    
  54.         }    
  55.     }    
  56.     catch (Exception ex)    
  57.     {    
  58.         toolStripStatusLabel1.Text = ex.Message;    
  59.        // MessageBox.Show(ex.Message);    
  60.     }    
  61. }    

Summary

In this article we learned how SMO helps to access the SQL operation in C#. We can use these namespaces and do whatever we want.

Up Next
    Ebook Download
    View all
    Learn
    View all