Here is a simple codesnippet which displays a list of databases in a listbox.
The BackupNow() method backups the selected database in the disk. The backup path is specified in
the appsettings section in the web.config.
GetConnection conn = new GetConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadHeader();
PopulateDatabaseTables();
GetBackupList();
}
}
private void PopulateDatabaseTables()
{
string tableName = string.Empty;
string sql = "select distinct db_name(s_mf.database_id) AS database_name"+
" from sys.master_files s_mf where s_mf.state = 0 ";
using (SqlConnection DBConn = conn.GetDBCon())
{
using (DataTable databases = new DataTable())
{
using (SqlDataAdapter dAd = new SqlDataAdapter(sql, DBConn))
{
dAd.Fill(databases);
}
ListBox1.DataSource = databases;
ListBox1.DataTextField = "database_name";
ListBox1.DataBind();
}
}
}
protected void BackUpNow(object sender, EventArgs e)
{
string tableName = this.ListBox1.SelectedItem.ToString();
string date = DateTime.Now.ToShortDateString();
date = date.Replace("/", "-");
date = date.Replace(" ", ":");
string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();
using ( SqlConnection DBConn = conn.GetDBCon())
{
string query = "backup database @tableName To Disk='" + path + "\\" + tableName + "[" + date + "]" + ".bak'";
SqlCommand cmd = new SqlCommand(query, DBConn);
cmd.Parameters.Add(new SqlParameter("@tableName", tableName));
cmd.ExecuteNonQuery();
}
GetBackupList();
lblMessage.Text = "Backup for <b>Database</b> successful!";
}
public void GetBackupList()
{
string path = ConfigurationManager.AppSettings.Get("DBBackupPath").ToString();
DirectoryInfo diFiles = new DirectoryInfo(path);
backupList.DataSource = diFiles.GetFiles("*.bak");
backupList.DataBind();
}