How to backup database programatically?

Ramy Mahrous 0 Tallied Votes 227 Views Share

Here's I wrote some code to backup your database
1- Add references (Microsoft.SqlServer.Smo and Microsoft.SqlServer.ConnectionInfo) to your project.
2- Call method BackupDatabase which takes to arguments database name and backup file path with extension .bak (preferable)

//This code developed by Ramy Mahrous 
//Its contents is provided "as is", without warranty.
//Add reference to Microsoft.SqlServer.Smo and Microsoft.SqlServer.ConnectionInfo
/// <summary>
/// Performs backup operation to database.
/// </summary>
/// <param name="databaseName">Database name to be backed up</param>
/// <param name="filePath">Backup file path with extension</param>
public void BackupDatabase(string databaseName, string filePath)
Server sqlServerInstance = new Server(
new Microsoft.SqlServer.Management.Common.ServerConnection(
new System.Data.SqlClient.SqlConnection("Data Source=.;Initial Catalog=Master;Integrated Security=True")));// your connection string I place mine for illustration.. DON'T HARDLY WRITE IT, pass it as argument or add it in application configuration 
Backup backupMgr = new Backup();
backupMgr.Devices.AddDevice(filePath, DeviceType.File);
backupMgr.Database = databaseName;
backupMgr.Action = BackupActionType.Database;
catch(Exception ex)
MessageBox.Show(ex.Message + " " + ex.InnerException);