SQL Server Database BackUp using C#
There are various ways to take the SQL Server database backup. You can take the database
backup using SQL Server backup wizard or using SQL Server BackUp Database
statement. Here I am going to describe how to take the SQL Server database backup
programatically using C# and SQL Server Management Objects (SMO).
In my previous posts, I explained Partial Methods,Contextual Keyword, C# Static Methods
and some other articles related to C#, [Link] and SQL Server .
SQL Server Management Objects (SMO) is a collection of objects that are designed for
programming all aspects of managing Microsoft SQL Server.
For taking the database backup using C#, you have to add the following references in your
application-
[Link]
[Link]
[Link]
[Link]
[Link]
In your .CS file you will have to use the following namespaces-
using [Link];
using [Link];
After using above namespaces, write the following code to take the database backup-
public void BackupDatabase(string databaseName, string userName, string password, string
serverName, string destinationPath)
{
//Define a Backup object variable.
Backup sqlBackup = new Backup();
//Specify the type of backup, the description, the name, and the database to
be backed up.
[Link] = [Link];
[Link] = "BackUp of:" + databaseName + "on" +
[Link]();
[Link] = "FullBackUp";
[Link] = databaseName;
//Declare a BackupDeviceItem
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath +
"[Link]", [Link]);
//Define Server connection
ServerConnection connection = new ServerConnection(serverName, userName,
password);
//To Avoid TimeOut Exception
Server sqlServer = new Server(connection);
[Link] = 60 * 60;
Database db = [Link][databaseName];
[Link] = true;
[Link] = true;
[Link] = true;
//Add the device to the Backup object.
[Link](deviceItem);
//Set the Incremental property to False to specify that this is a full
database backup.
[Link] = false;
[Link] = [Link](3);
//Specify that the log must be truncated after the backup is complete.
[Link] = [Link];
[Link] = false;
//Run SqlBackup to perform the full database backup on the instance of SQL
Server.
[Link](sqlServer);
//Remove the backup device from the Backup object.
[Link](deviceItem);
}
Happy coding!!