I have developed an ASP.NET Core web application, I need to write a C# method to allow the end user to download or save the SQL Server database full backup on his local computer. Moreover, I need to upload that database backup to restore a database.
Here is an example C# method that I wrote to download and save only one table of data in Excel format. Now I want to write another method to allow the user to download and save the all table full-backup as a .bak
file on his local computer.
Please guide how to achieve this, thank you.
[DisplayName("Export Data To Excel")]
[Authorize(policy: "HasAccess")]
public class ExportDataToExcelController : BaseController
{
public ExportDataToExcelController(HoshmandDBContext context) : base(context)
{
}
// ----Export Patient Data -----------------------------
public IActionResult ExportPatientDataToExcel()
{
DataTable patientTable = new DataTable("Patients_Data");
patientTable.Columns.AddRange(new DataColumn[9]
{
new DataColumn("Patient ID"),
new DataColumn("First Name"),
});
var patientsList = _context.PatientTbs.Include(a => a.Doctor).ToList();
foreach (var patient in patientsList)
{
patientTable.Rows.Add(patient.PatientId, patient.FirstName);
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(patientTable);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Patients Data " + GetLocalDateTime().Date.ToShortDateString() + "_" + ".xlsx");
}
}
}
}
Here is the user interface screenshot that I can download only one table of data in Excel format:
Here is an example user interface for restoring the database backup: