restore and backup db in csharp

To backup and restore a database in C#, you can use the SqlConnection class which is provided by the System.Data.SqlClient namespace. You can use the SqlCommand class to execute backup and restore commands.

Here's an example of how you can backup a database:

main.cs
string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
string backupPath = @"C:\Backup\MyDatabase.bak";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    string backupQuery = "BACKUP DATABASE [" + connection.Database + "] TO DISK='" + backupPath + "'";

    using (SqlCommand command = new SqlCommand(backupQuery, connection))
    {
        command.ExecuteNonQuery();
    }
}
489 chars
15 lines

Here's an example of how you can restore a database:

main.cs
string connectionString = "Data Source=ServerName;Initial Catalog=master;User ID=UserName;Password=Password";
string backupPath = @"C:\Backup\MyDatabase.bak";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    // Kill all processes on the target database
    string killConnectionsQuery = "USE [master]; " +
                                  "DECLARE @kill varchar(8000) = ''; " +
                                  "SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';' " +
                                  "FROM sys.dm_exec_sessions WHERE database_id = DB_ID('" + connection.Database + "') " +
                                  "EXEC(@kill);";

    using (SqlCommand command = new SqlCommand(killConnectionsQuery, connection))
    {
        command.ExecuteNonQuery();
    }

    // Restore database
    string restoreQuery = "USE [master]; " +
                          "ALTER DATABASE [" + connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; " +
                          "RESTORE DATABASE [" + connection.Database + "] " +
                          "FROM DISK='" + backupPath + "' " +
                          "WITH REPLACE, " +
                          "MOVE '" + connection.Database + "' TO 'C:\\Data\\" + connection.Database + ".mdf', " +
                          "MOVE '" + connection.Database + "_log' TO 'C:\\Data\\" + connection.Database + "_log.ldf'; " +
                          "ALTER DATABASE [" + connection.Database + "] SET MULTI_USER;";

    using (SqlCommand command = new SqlCommand(restoreQuery, connection))
    {
        command.ExecuteNonQuery();
    }
}
1666 chars
35 lines

Note: In the restore example, we first kill all connections to the target database to avoid any conflicts during the restore process.

related categories

gistlibby LogSnag