using Microsoft.SqlServer.Management;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Windows.Forms;
public void BackupDatabase(String databaseName, String userName, String password, String serverName, String destinationPath)
{
try
{
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);
//Backup bu = new Backup();
//bu.Database = databaseName;
//bu.Devices.Add(deviceItem);
//bu.Initialize = true;
//bu.PercentCompleteNotification = 10;
//// add percent complete and complete event handlers
//bu.PercentComplete += new PercentCompleteEventHandler(Backup_PercentComplete);
//bu.Complete += new ServerMessageEventHandler(Backup_Complete);
//ServerConnection connection = new ServerConnection(serverName,userName,password);
ServerConnection connection = new ServerConnection(serverName);
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);
MessageBox.Show("Database Backup success....\nBackup file in " + destinationPath + ".", "Backup success", MessageBoxButtons.OK, MessageBoxIcon.None);
}
catch(Exception ex)
{
MessageBox.Show("Database Backup failed....", "Backup failed\n"+ex.InnerException.ToString () +"", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
http://www.prpraveen.blogspot.com