In this article, I will explain how to create a backup of a SQL Server database in ASP.NET using C#.

To better understand this tutorial, you should know following C# programming topic:

First, let’s create a web form Asp.NET solution, and then add a button to the default page as shown below:

database backup c#

 

HTML:

    <div style="align-content: center">
        <asp:Button ID="btnBackup" runat="server" Text="Create Backup" />
    </div>

Now let’s look at the button click event:

C#:

        protected void btnBackup_Click(object sender, EventArgs e)
        {
            SqlConnection sqlconn = new SqlConnection("Data Source=TutorialsPanel-PC\SQLEXPRESS;Initial Catalog=TutorialsPanel;Integrated Security=True;Pooling=False");
            SqlCommand sqlcmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            DataTable dt = new DataTable();

            // Backup destibation
            string backupDestination = "C:\SQLBackUpFolder";

            // check if backup folder exist, otherwise create it.
            if (!System.IO.Directory.Exists(backupDestination))
            {
                System.IO.Directory.CreateDirectory("D:\SQLBackUpFolder");
            }
            try
            {
                sqlconn.Open();
                sqlcmd = new SqlCommand("backup database TutorialsPanel to disk='" + backupDestination + "\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlconn);
                sqlcmd.ExecuteNonQuery();
                //Close connection
                sqlconn.Close();
                Response.Write("Backup database successfully");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

Related Articles:

Last modified: March 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.