In this article I am going to explain how we can take
backup of our Data Base using c#, asp.net.
Below is my output screen:

Image 1.
Below is my aspx:
<%@ Page
Language="C#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs"
Inherits="_Default"
%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Backup and Restore DataBase</title>
</head>
<body>
<form
id="form1"
runat="server">
<div>
<table
cellpadding="10"
cellspacing="10"
style="border: solid 10px red; background-color: Skyblue;"
width="90%" align="center">
<tr>
<td style="height: 35px; background-color:
Yellow; font-weight:
bold; font-size:
16pt;
font-family:
Times New Roman; color: Red" align="center">
Backup SQL Server DataBase
</td>
</tr>
<tr>
<td align="center">
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
<asp:Button ID="btnBackup" runat="server" Text="Backup DataBase" OnClick="btnBackup_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
My aspx.cs code is:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using
System.Web.UI.HtmlControls;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial
class _Default
: System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void
Page_Load(object sender, EventArgs e)
{
}
protected
void btnBackup_Click(object
sender, EventArgs e)
{
//IF SQL Server Authentication then Connection
String
//con.ConnectionString =
@"Server=MyPC\SqlServer2k8;database=" + YourDBName +
";uid=sa;pwd=password;";
//IF Window Authentication then Connection
String
con.ConnectionString = @"Server=MyPC\SqlServer2k8;database=Test;Integrated
Security=true;";
string backupDIR = "H:\\BackupDB";
if (!System.IO.Directory.Exists(backupDIR))
{
System.IO.Directory.CreateDirectory(backupDIR);
}
try
{
con.Open();
sqlcmd = new
SqlCommand("backup
database test to disk='" + backupDIR + "\\"
+ DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", con);
sqlcmd.ExecuteNonQuery();
con.Close();
lblError.Text = "Backup database successfully";
}
catch (Exception
ex)
{
lblError.Text = "Error Occured During DB backup process
!<br>" + ex.ToString();
}
}
}
Check your backup
directory:

Image 2.