ADO.NET

How to take database backup using c#?

How to take database backup using c#?, someone asked me to explain?

A  backup, or the process of backing up, refers to the copying and archiving of computer data so it may be used to restore the original after a data loss event . we are taking backing using SQL Server Management Studio .You can create a SQL Server database backup SQL Server through coding using c#.

Here you need to set connection string by manual.

   private void Backup()
        {
            SqlConnection con = new SqlConnection();
            SqlCommand sqlcmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            DataTable dt = new DataTable();
            string connstring = "Data Source=server;Initial Catalog=database;User Id=username;Password=password";
            con.ConnectionString = connstring;
            var path = Path.Combine(Server.MapPath("~/Upload Images"));
            string backupDIR = path;//"C:\\BackupDB";
            if (!System.IO.Directory.Exists(backupDIR))
            {
                System.IO.Directory.CreateDirectory(backupDIR);
            }
            System.IO.Directory.GetDirectoryRoot(backupDIR);
            con.Open();
            sqlcmd = new SqlCommand((Convert.ToString("backup database mydatabase to disk='") + backupDIR) + "\\" +
                                         DateTime.Now.ToString("ddMMyyyy_HHmmss") +       ".Bak'", con);
            sqlcmd.ExecuteNonQuery();
            con.Close();
}

Post your comments / questions