Click here to Skip to main content
15,896,118 members
Articles / Database Development / SQL Server

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 312.3K   22.4K   88  
SQL Server 2005 database backup and restore using C#, .NET 2.0, and SMO.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

namespace SqlServerBackupRestore
{
    public class BackupHelper
    {
        public BackupHelper()
        {

        }

        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);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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