Click here to Skip to main content
Licence CPOL
First Posted 26 May 2008
Views 114,641
Downloads 8,495
Bookmarked 73 times

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

By | 7 Jun 2008 | Article
SQL Server 2005 database backup and restore using C#, .NET 2.0, and SMO.
 
Part of The SQL Zone sponsored by
See Also

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

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

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:

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)

About the Author

Bappi M Ahmed

Software Developer
SDL Tridion
Netherlands Netherlands

Member

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/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionTesting Pinmemberblochjaved1233:14 22 May '12  
Questioni am using ms sql 2008 R2 version Pinmemberrajesh@198919:45 11 Apr '12  
QuestionProgressbar for showing backup/restore progress Pinmembermilindgs207:14 3 Apr '12  
QuestionDB delay after restore Pinmemberquiet.step2:11 25 Jan '12  
QuestionAuthentican issue - easy solution Pinmembersaberint21:51 11 Oct '11  
AnswerRe: Authentican issue - easy solution Pinmemberksbaboo5:46 23 Feb '12  
GeneralMy vote of 5 PinmemberDaniel Vlasceanu9:20 19 May '11  
Generalbackup and restore database Pinmembersabelopumzile0:51 26 Aug '10  
Questionhi pls help me.. PinmemberVaghasiya Nilesh3:19 12 Jul '10  
GeneralError:Database is in use PinmemberHamid Darabi2:38 4 Jan '10  
GeneralRe: Error:Database is in use PinmemberMember 41578924:23 13 Mar '10  
GeneralError creating backup PinmemberAlCsharp20:57 17 Oct '09  
GeneralRe: Error creating backup PinmemberNouman_gcu0:58 21 Oct '09  
Generalvb.net Pinmemberananthkind10:18 30 Sep '09  
GeneralOperating System Error 5 (Access is Denied) PinmemberSandeep N. Pamnani2:01 7 Sep '09  
GeneralRe: Operating System Error 5 (Access is Denied) PinmemberNouman_gcu1:01 21 Oct '09  
GeneralRe: Operating System Error 5 (Access is Denied) PinmemberTedChangKorea22:06 26 Oct '09  
Generalexception on sqlRestore method using C#.net 3.5 and ms sql server 2005 [modified] PinmemberMember 38114102:32 30 Jun '09  
GeneralRuntime exception in sqlRestore method using C#.net 3.5 and sql server 2005 on a windows application PinmemberMember 381141021:42 29 Jun '09  
QuestionsqlRestore.SqlRestore(sqlServer) error PinmemberMaciej Gebski22:42 4 Jun '09  
AnswerRe: sqlRestore.SqlRestore(sqlServer) error PinmemberTheChange3:24 5 Aug '09  
GeneralVery good. Pinmemberitayl12:14 27 May '09  
GeneralSMO vs SQLDMO Pinmemberqwe12343:40 20 Jan '09  
Generalerror Pinmemberpokiri20:12 4 Jan '09  
Questioni m getting error : Backup failed for Server 'myservername' PinmemberSandeep Ramani21:42 26 Nov '08  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 8 Jun 2008
Article Copyright 2008 by Bappi M Ahmed
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid