Here, we will learn about taking the backup of database programmatically using c#. We will take the backup of a single database in our tutorial.
Prerequisite
- Basic knowledge of C#
- Basic knowledge of ASP.NET MVC
Create a new project in ASP.NET MVC and open the HomeController and replace the code with it.
public class HomeController : Controller { public ActionResult Index() => View(); public async Task<JsonResult> GenerateBackupFile() { try { await Task.Run(() => { string dbConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; string backupFolderName = ConfigurationManager.AppSettings["BackUpFolder"].ToString(); if (!Directory.Exists(backupFolderName)) Directory.CreateDirectory(backupFolderName); SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(dbConnectionString); var backupFileName = $"{backupFolderName}{sqlConnectionStringBuilder.InitialCatalog}-{DateTime.Now.ToString("yyyy-MM-dd")}.bak"; if (System.IO.File.Exists(backupFileName)) System.IO.File.Delete(backupFileName); using (SqlConnection connection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString)) { string backupQuery = $"BACKUP DATABASE {sqlConnectionStringBuilder.InitialCatalog} TO DISK='{backupFileName}'"; using (SqlCommand command = new SqlCommand(backupQuery, connection)) { connection.Open(); command.ExecuteNonQuery(); } } }); return Json(true, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(false, JsonRequestBehavior.AllowGet); } } }
Open the Index.cshtml and replace the code in it.
@{ ViewBag.Title = "Home Page"; } <button class="btn btn-success" id="btnBeginBackup" style="margin-top:60px">Take Backup</button> <script> $(document).on('click', '#btnBeginBackup', function () { showLoader(); $.ajax({ url: '/Home/GenerateBackupFile', type: 'GET', success: function (res) { hideLoader(); if (res) toastr.success("Backup taken successfully"); else toastr.error("Backup failed"); }, error: function (err) { hideLoader(); toastr.error("Something went wrong. Please contact administrator"); } }); }); </script>
Finally, at last, open the _Layout.cshtml and replace the code in it.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") <link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet"> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script> <style> #loading { position: fixed; top: -50%; left: -50%; width: 200%; height: 200%; background: rgba(241, 241, 241, 0.48); z-index: 2000; overflow: hidden; } #loading img { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } </style> </head> <body> <div id="loading"> <img src="~/Content/ajax-loader.gif" /> </div> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Database Backup Demo", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>© @DateTime.Now.Year - My ASP.NET Application</p> </footer> </div> @RenderSection("scripts", required: false) </body> </html> <script> function showLoader() { $('#loading').show(); } function hideLoader() { $('#loading').fadeOut(); } $(document).ready(function () { hideLoader(); }); </script>
Output: