Code in C# to create a backup of a database in SQL server and restore it

Posted By Venu Thomas

Here they left a code in C # very useful when making your applications with databases in SQL server can support the database and restore it.

Support code for a button:

private void btnBackUp_Click(object sender, EventArgs e)
{
    bool bBackUpStatus = true;

    Cursor.Current = Cursors.WaitCursor; 

     if (Directory.Exists(@"c:\SQLBackup"))
        {
            if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
            {
                if (MessageBox.Show(@"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    File.Delete(@"c:\SQLBackup\wcBackUp1.bak");
                }
                else
                    bBackUpStatus = false;
            }
        }
        else
            Directory.CreateDirectory(@"c:\SQLBackup");

        if (bFileStatus)
        {
            //Connect to DB
            SqlConnection connect;
            string con = "Data Source = localhost; Initial Catalog=dbWiseCodes ;Integrated Security = True;";
            connect = new SqlConnection(con);
            connect.Open();
            //----------------------------------------------------------------------------------------------------

            //Execute SQL---------------
            SqlCommand command;
            command = new SqlCommand(@"backup database dbWiseCodes to disk ='c:\SQLBackup\wcBackUp1.bak' with init,stats=10", connect);
            command.ExecuteNonQuery();
            //-------------------------------------------------------------------------------------------------------------------------------

            connect.Close();

            MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
}

Code for a button to restore:


private void btnRestore_Click(object sender, EventArgs e)
{

    Cursor.Current = Cursors.WaitCursor;

    try
    {
        if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
        {
            if (MessageBox.Show("Are you sure you restore?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //Connect SQL-----------
                SqlConnection connect;
                string con = "Data Source = localhost; Initial Catalog=master ;Integrated Security = True;";
                connect = new SqlConnection(con);
                connect.Open();
                //-----------------------------------------------------------------------------------------

                //Excute SQL----------------
                SqlCommand command;
          command = new SqlCommand("use master", connect);
            command.ExecuteNonQuery();
                command = new SqlCommand(@"restore database dbWiseCodes01 from disk = 'c:\SQLBackup\wcBackUp1.bak'", connect);
                command.ExecuteNonQuery();
                //--------------------------------------------------------------------------------------------------------
                connect.Close();

                MessageBox.Show("Has been restored database", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        else
            MessageBox.Show(@"Do not make any endorsement above (or is not in the correct path)", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
    catch (Exception exp)
    {
        MessageBox.Show(exp.Message);
    }

}

Tags: , , , ,

  •  
  • Share with others:

    Thanks for visiting us! If you enjoyed these icons please feel free to share them! Or if you want to know what's going on with WiseCodes.com, follow us!

    12 Responses to “Code in C# to create a backup of a database in SQL server and restore it”

    1. Thanks Venu. It is really going to be helpful

    2. Ram your flag on August 21st, 2009 at 9:42 AM
    3. Very nice post! I never knew that I could make backups directly from C#. Thanks!

    4. seesharpgears your flag on August 27th, 2009 at 12:58 PM
    5. System.Data.SqlClient.SqlException was unhandled
      Message=”Exclusive access could not be obtained because the database is in use.\r\nRESTORE DATABASE is terminating abnormally.”
      Source=”.Net SqlClient Data Provider”
      ErrorCode=-2146232060
      Class=16
      LineNumber=1
      Number=3101
      Procedure=”"
      Server=”localhost”
      State=1
      StackTrace:
      at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
      at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
      at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
      at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
      at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
      at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
      at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
      at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
      at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
      at Libra.frmMdi.mnuiRestore_Click(Object sender, EventArgs e) in H:\Libra\Libra\Libra\MDI.cs:line 132
      at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
      at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
      at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
      at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
      at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
      at System.Windows.Forms.ToolStripItem.ProcessDialogKey(Keys keyData)
      at System.Windows.Forms.ToolStripDropDownItem.ProcessDialogKey(Keys keyData)
      at System.Windows.Forms.ToolStrip.ProcessDialogKey(Keys keyData)
      at System.Windows.Forms.ToolStripDropDown.ProcessDialogKey(Keys keyData)
      at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
      at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
      at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)
      at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(MSG& msg)
      at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
      at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
      at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
      at System.Windows.Forms.Application.Run(Form mainForm)
      at Libra.Program.Main() in H:\Libra\Libra\Libra\Program.cs:line 17
      at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
      at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
      at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
      at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
      at System.Threading.ThreadHelper.ThreadStart()

      m getting this error please help

    6. waheeb your flag on November 4th, 2009 at 2:18 PM
    7. I guess I’m going to need to read up some more, but this was a really good spring board.

    8. Ubuntu Maverick Meerkat your flag on April 15th, 2010 at 1:56 PM
    9. Terrific work! This is the type of information that should be shared around the web. Shame on the search engines for not positioning this post higher!

    10. inexpensive furniture your flag on June 20th, 2010 at 5:18 PM
    11. The file ‘C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\DATA\dbWiseCodes.mdf’ cannot be overwritten. It is being used by database ‘dbWiseCodes’.
      File ‘dbWiseCodes’ cannot be restored to ‘C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\DATA\dbWiseCodes.mdf’. Use WITH MOVE to identify a valid location for the file.
      The file ‘C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\DATA\dbWiseCodes_log.ldf’ cannot be overwritten. It is being used by database ‘dbWiseCodes’.
      File ‘dbWiseCodes_log’ cannot be restored to ‘C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\DATA\dbWiseCodes_log.ldf’. Use WITH MOVE to identify a valid location for the file.
      Problems were identified while planning for the RESTORE statement. Previous messages provide details.
      RESTORE DATABASE is terminating abnormally.

    12. Nishant your flag on June 25th, 2010 at 4:45 PM
    13. Hello… I can not access your rss feed… Something trouble? Can you fix it? Thanks

    14. chemotherapy lung cancer your flag on August 10th, 2010 at 8:51 AM
    15. I am tired of these make money online schemes. What works for me is to submit my content to article sites and get web traffic.

    16. best article directory your flag on August 17th, 2010 at 12:39 AM
    17. Great info – very informative will bookmark.

    18. bmx forks your flag on August 22nd, 2010 at 9:18 AM
    19. Hi, admin, can I copy some information from the post?

    20. how to lose weight your flag on August 27th, 2010 at 11:16 AM
    21. Interesting, very interesting. Take posting this good information.

    22. Gladis Shawe your flag on August 29th, 2010 at 7:41 AM
    23. Super post indeed. My mother has been searching for this update.

    24. free hosting no ads your flag on September 12th, 2011 at 3:07 AM

    Leave a Reply

    Anti-Spam Protection by WP-SpamFree

    Locations of visitors to this page eXTReMe Tracker