Try this:
private void DatabaseBackup()
{
string strDate = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');
string[] strTime = DateTime.Now.TimeOfDay.ToString().Split(':');
string strDateTime = strDate + " " + strTime[0].PadLeft(2, '0') + strTime[1].PadLeft(2, '0');
try
{
string backupPath = txtBackupLocation.Text.Trim() + "\\" + strDateTime + ".bak";
int retVal = 0;
DatabaseBackup(backupPath);
if (retVal != 0)
{
btnBackupDatabase.Enabled = false;
lblBackupStatus.Text = "Database backup successful.";
MessageBox.Show("Backup of database completed successfully." + Environment.NewLine + backupPath, Program.MESSAGEBOXTITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
btnClose.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show("Error [Database Backup]: " + Environment.NewLine + ex.Message, Program.MESSAGEBOXTITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
lblBackupStatus.Text = "Database backup failed.";
}
}
public int DatabaseBackup(string backupPath)
{
int retVal = 0;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"Backup Database To Disk = '" + backupPath + "' WITH INIT";
try
{
conn.Open();
cmd.Connection = conn;
retVal = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
conn.Close();
}
return retVal;
}