Chưa phân loại

Restore SQL Server Database Using C#

In previous post SQL Server Database BackUp using C#, I explained how to take backup of SQL Server database using C#. Today I am going to describe how to restore SQL Server database backup programmatically using C# and SQL Server Management Objects (SMO).

You can also check more articles related to C#, ASP.Net , SQL Server and others.

SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server.
For restoring the backup using C#, you have to add the following references in your application-


In your .CS file you will have to use the following namespaces-

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

After using above namespaces, write the following code to take the database backup-

public void RestoreDatabase(string databaseName, string userName, string password, string serverName, string sourcePath)
                //Define a Backup object variable.
                Restore sqlRestore = new Restore();

                //Specify the type of backup, the description, the name, and the database to be backed up.
                sqlRestore.Action = RestoreActionType.Database;
                sqlRestore.NoRecovery = false;
                sqlRestore.Database = databaseName;
                sqlRestore.ReplaceDatabase = true;
                sqlRestore.PercentCompleteNotification = 10;

                //Declare a BackupDeviceItem
                BackupDeviceItem deviceItem = new BackupDeviceItem(sourcePath, DeviceType.File);
                //Define Server connection
                ServerConnection connection = new ServerConnection(serverName, userName, password);
                //To Avoid TimeOut Exception
                Server sqlServer = new Server(connection);
                sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
                sqlRestore.Checksum = true;
                sqlRestore.ContinueAfterError = true;
                //Add the device to the Restore object.

                //Run SqlRestore to perform the database restore on the instance of SQL Server.
                //Remove the restore device from the restore object.
            catch(Exception ex) {

Happy coding!!



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s