To back up the database:
String connectionString = "server= server name; database= database name; uid= login name; pwd= login Password"; Login name and password to find in SQL Server
private void Btnbackdatabase_click (object sender, EventArgs e)
{
Try
{
SaveFileDialog SF = new SaveFileDialog ();
DialogResult dr = sf. ShowDialog ();
if (dr = = DialogResult.OK)
{
String path = SF. FileName;
String sql = "BACKUP database name to DISK = '" + Path + "'";
SqlConnection con = new SqlConnection (connectionString);
Con. Open ();
SqlCommand cmd = new SqlCommand (sql, con);
Cmd. ExecuteNonQuery ();
MessageBox.Show ("Database backup succeeded");
Con. Close ();
}
}
catch (Exception ex)
{
MessageBox.Show (ex. Message.tostring ());
}
}
Database restore:
private void Btnrestore_click (object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog ();
DialogResult dr = Ofd. ShowDialog ();
if (dr = = DialogResult.OK)
{
Try
{
String cmdtext = @ "Restore Databa SE database name from disk= ' "+ ofd. FileName + "'";
SqlConnection con = new SqlConnection (connectionString);
Con. Open ();
String setoffline = "Alter database name set Offline with rollback immediate";
String setonline = "Alter database name set Online with Rollback immediate";
String sql = setoffline + cmdtext + setonline;
SqlCommand cmd = new SqlCommand (sql, con);
Cmd. ExecuteNonQuery ();
Con. Close ();
}
catch (Exception ex)
{
MessageBox.Show (ex). Message);
}
}
}
C # Backup and restore of SQL Server databases