Click here to Skip to main content
11,411,922 members (60,591 online)
Click here to Skip to main content

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

, 7 Jun 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
SQL Server 2005 database backup and restore using C#, .NET 2.0, and SMO.


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.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


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:" + 
    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.Incremental = false;

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

    sqlBackup.FormatMedia = false;


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.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);
    db = sqlServer.Databases[databaseName];

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.


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.


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
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:

Comments and Discussions

QuestionRestore failed for Server '.\sql2008' Pinmemberamir farashah24-Jan-15 8:49 
Questionlink download die PinmemberMember 245846726-Jun-14 0:06 
QuestionMy vote of 5 Pinprofessionalabbaspirmoradi8-Sep-13 8:22 
GeneralMy vote of 3 Pinmemberbunzitop26-Mar-13 4:41 
GeneralMy vote of 5 PinmemberMember 966765523-Jan-13 19:39 
AnswerAbout restore and backup Pinmemberarunarw6-Aug-12 6:26 
GeneralRe: About restore and backup Pinmembersk. safaruddin17-Aug-12 22:27 
QuestionSQL Server 2005 Database Backup and Restore using C# and .NET 2.0 (View) Author Bappi M Ahmed Pinmembervinhhc17-Jul-12 16:33 
AnswerSQL Server 2005 Database Backup and Restore using C# and .NET 2.0 (View) Author Bappi M Ahmed Pinmembervinhhc17-Jul-12 16:18 
QuestionTesting Pinmemberblochjaved12322-May-12 4:14 
Questioni am using ms sql 2008 R2 version Pinmemberrajesh@198911-Apr-12 20:45 
QuestionProgressbar for showing backup/restore progress Pinmembermilindgs203-Apr-12 8:14 
QuestionDB delay after restore Pinmemberquiet.step25-Jan-12 3:11 
QuestionAuthentican issue - easy solution Pinmembersaberint11-Oct-11 22:51 
AnswerRe: Authentican issue - easy solution Pinmemberksbaboo23-Feb-12 6:46 
GeneralMy vote of 5 PinmemberDaniel Vlasceanu19-May-11 10:20 
Generalbackup and restore database Pinmembersabelopumzile26-Aug-10 1:51 
Questionhi pls help me.. PinmemberVaghasiya Nilesh12-Jul-10 4:19 
GeneralError:Database is in use PinmemberHamid Darabi4-Jan-10 3:38 
GeneralRe: Error:Database is in use PinmemberMember 415789213-Mar-10 5:23 
GeneralError creating backup PinmemberAlCsharp17-Oct-09 21:57 
GeneralRe: Error creating backup PinmemberNouman_gcu21-Oct-09 1:58 Pinmemberananthkind30-Sep-09 11:18 
GeneralOperating System Error 5 (Access is Denied) PinmemberSandeep N. Pamnani7-Sep-09 3:01 
GeneralRe: Operating System Error 5 (Access is Denied) PinmemberNouman_gcu21-Oct-09 2:01 

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.

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