Click here to Skip to main content
15,886,199 members
Articles / Database Development / SQL Server
Article

SQL Server 2005 Database Backup and Restore using C# and .NET 2.0

Rate me:
Please Sign up or sign in to vote.
4.24/5 (26 votes)
7 Jun 2008CPOL1 min read 311.7K   22.4K   88   61
SQL Server 2005 database backup and restore using C#, .NET 2.0, and SMO.

Introduction

The following article describes accessing a SQL Server 2005 database backup and restoring it programmatically using C#.NET 2.0 and SMO. This article provides coding samples to perform the task.

SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server.

The following namespaces can be used to access SQL Server 2005 programmatically:

  • Microsoft.SqlServer.management
  • Microsoft.SqlServer.Management.NotificationServices
  • Microsoft.SqlServer.Management.Smo
  • Microsoft.SqlServer.Management.Smo.Agent
  • Microsoft.SqlServer.Management.Smo.Broker
  • Microsoft.SqlServer.Management.Smo.Mail
  • Microsoft.SqlServer.Management.Smo.RegisteredServers
  • Microsoft.SqlServer.Management.Smo.Wmi
  • Microsoft.SqlServer.Management.Trace

Pre-Requisite

You need to reference the following namespaces before using this code:

  • Microsoft.SqlServer.Management.Smo;
  • Microsoft.SqlServer.Management.Common;

I used these two class to perform the backup and restore operations:

  • Microsoft.SqlServer.Management.Smo.Backup
  • Microsoft.SqlServer.Management.Smo.Restore

For more information, regarding these two class, check MSDN:

Backup database

C#
public void BackupDatabase(String databaseName, String userName, 
            String password, String serverName, String destinationPath)
{
    Backup sqlBackup = new Backup();
    
    sqlBackup.Action = BackupActionType.Database;
    sqlBackup.BackupSetDescription = "ArchiveDataBase:" + 
                                     DateTime.Now.ToShortDateString();
    sqlBackup.BackupSetName = "Archive";

    sqlBackup.Database = databaseName;

    BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);
    
    Database db = sqlServer.Databases[databaseName];
    
    sqlBackup.Initialize = true;
    sqlBackup.Checksum = true;
    sqlBackup.ContinueAfterError = true;
    
    sqlBackup.Devices.Add(deviceItem);
    sqlBackup.Incremental = false;

    sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
    sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

    sqlBackup.FormatMedia = false;

    sqlBackup.SqlBackup(sqlServer);
}

Restore Database

C#
public void RestoreDatabase(String databaseName, String filePath, 
       String serverName, String userName, String password, 
       String dataFilePath, String logFilePath)
{
    Restore sqlRestore = new Restore();
    
    BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
    sqlRestore.Devices.Add(deviceItem);
    sqlRestore.Database = databaseName;

    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);

    Database db = sqlServer.Databases[databaseName];
    sqlRestore.Action = RestoreActionType.Database;
    String dataFileLocation = dataFilePath + databaseName + ".mdf";
    String logFileLocation = logFilePath + databaseName + "_Log.ldf";
    db = sqlServer.Databases[databaseName];
    RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);
    
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName+"_log", logFileLocation));
    sqlRestore.ReplaceDatabase = true;
    sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
    sqlRestore.PercentCompleteNotification = 10;
    sqlRestore.PercentComplete += 
       new PercentCompleteEventHandler(sqlRestore_PercentComplete);
            
    sqlRestore.SqlRestore(sqlServer);
    db = sqlServer.Databases[databaseName];
    db.SetOnline();
    sqlServer.Refresh();
}

The portion of code uses full backup features. If you want, you can perform incremental and differential backup as well.

Updates: June 8, 2008

In order to use this code, your SQL Server authentication mode needs to be configured as Mixed Mode authentication. If you use Windows Authentication, then you need to modify the ServerConnection:

C#
SqlConnection sqlCon = new SqlConnection ("Data Source=Bappi; Integrated Security=True;");
ServerConnection connection = new ServerConnection(sqlCon);

Modify the ServerConnection portion of both code samples using this code in order to use Windows Security.

Conclusion

As this code uses the SQL Server 2005 backup/restore facility, the code follows the rules of SQL Server 2005 while backing up or restoring databases.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer SDL Tridion
Netherlands Netherlands
Software Developer with extensive experience in Software Development. Six years of Job experience in different positions. Eight years of practical experience in .net development. Experience in Distributed Application Development, Service Oriented Application Development and Smart Client Application development using .net framework.

More About Me:
http://iambappi.wordpress.com
http://iambappi.spaces.live.com/

Comments and Discussions

 
AnswerRe: sqlRestore.SqlRestore(sqlServer) error Pin
y.aitelmaati5-Aug-09 3:24
y.aitelmaati5-Aug-09 3:24 
GeneralRe: sqlRestore.SqlRestore(sqlServer) error Pin
kanchan.srajput2-Jan-13 0:12
kanchan.srajput2-Jan-13 0:12 
GeneralVery good. Pin
itayl27-May-09 12:14
itayl27-May-09 12:14 
GeneralSMO vs SQLDMO Pin
qwe123420-Jan-09 3:40
qwe123420-Jan-09 3:40 
Generalerror Pin
pokiri4-Jan-09 20:12
pokiri4-Jan-09 20:12 
Questioni m getting error : Backup failed for Server 'myservername' Pin
Sandeepkumar Ramani26-Nov-08 21:42
Sandeepkumar Ramani26-Nov-08 21:42 
QuestionRe: i m getting error : Backup failed for Server 'myservername' Pin
Darwin Tenk12-May-09 2:11
Darwin Tenk12-May-09 2:11 
QuestionRestore failed for Server 'SHAM/EXPRESS'. Pin
Member 380125920-Nov-08 23:19
Member 380125920-Nov-08 23:19 
Hi Bappi,
Nice article. But while calling the " sqlRestore.SqlRestore(sqlServer);" i am getting the following error "Restore failed for Server 'SHAM/EXPRESS'."



Plz help me with this regard..

Regards
Shamveel Ahmed
GeneralIssues with windows authentication Pin
bigsybiggins15-Oct-08 3:49
bigsybiggins15-Oct-08 3:49 
AnswerRe: Issues with windows authentication Pin
srabik4-Feb-09 13:59
srabik4-Feb-09 13:59 
GeneralRe: Issues with windows authentication Pin
Ahmed.lpo12-Mar-11 3:23
Ahmed.lpo12-Mar-11 3:23 
Generalhelpful Pin
shahed hasan16-Sep-08 23:42
shahed hasan16-Sep-08 23:42 
Questionproblem with logical file names. Pin
Member 232138520-Aug-08 19:44
Member 232138520-Aug-08 19:44 
AnswerRe: problem with logical file names. Pin
Bappi M Ahmed7-Oct-08 18:27
Bappi M Ahmed7-Oct-08 18:27 
GeneralRe: problem with logical file names. Pin
MCAST7623-Mar-09 13:27
MCAST7623-Mar-09 13:27 
GeneralGet error in restore Pin
jay.net20056-Aug-08 20:03
jay.net20056-Aug-08 20:03 
Generalhi friends Pin
prabhakaraan.s1-Aug-08 18:29
prabhakaraan.s1-Aug-08 18:29 
Generalplease help me Pin
prabhakaraan.s31-Jul-08 0:22
prabhakaraan.s31-Jul-08 0:22 
GeneralGreat work.... Pin
Member 122844819-Jul-08 3:45
Member 122844819-Jul-08 3:45 
QuestionNice article Pin
setu_raas12-Jun-08 5:04
setu_raas12-Jun-08 5:04 
AnswerRe: Nice article Pin
Bappi M Ahmed12-Jun-08 22:47
Bappi M Ahmed12-Jun-08 22:47 
Generalhi bappi please help me Pin
prabhakaraan.s1-Aug-08 1:46
prabhakaraan.s1-Aug-08 1:46 
Questionone error!!!!!!!! Pin
m0rteza8-Jun-08 4:21
m0rteza8-Jun-08 4:21 
AnswerRe: one error!!!!!!!! Pin
Bappi M Ahmed9-Jun-08 19:08
Bappi M Ahmed9-Jun-08 19:08 
GeneralRe: one error!!!!!!!! Pin
Member 232138520-Aug-08 6:43
Member 232138520-Aug-08 6:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.