原文发布时间为:2008-10-25 —— 来源于本人的百度文章 [由搬家工具导入]
数据库备份与还原c#.net实现:
页面上面有 备份,还原,下拉菜单(浏览备份文件夹下面的所有文件名),删除(删除备份),这四个控件。。。。。备份的时候把 时间转化成字符串格式 然后作为文件名保存 防止重复。
前台代码:
<%@ 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>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="备份" /><br />
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList><br />
<br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="还原" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="删除" /></div>
</form>
</body>
</html>
后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindFileName();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "Backup Database pubs to DISK='" + Server.MapPath("App_Data//BackUp//pubs" + DateTime.Now.ToString("yyyyMMddhhmmss")) + "'";
SqlConnection pubsConn = new SqlConnection("Server=.\SQLEXPRESS;Database=pubs;Integrated Security=True");
SqlCommand cmd = new SqlCommand(sql, pubsConn);
pubsConn.Open();
int a=cmd.ExecuteNonQuery();
if (a == -1)
{
Response.Write("success!");
}
else
{
Response.Write("fail!");
}
pubsConn.Close();
BindFileName();
}
public void BindFileName()
{
DropDownList1.Items.Clear();
string path = Server.MapPath("App_Data//BackUp");
DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo fi in di.GetFiles())
{
ListItem li=new ListItem();
li.Value=fi.FullName;
li.Text=fi.Name;
DropDownList1.Items.Add(li);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string sql = "Restore Database pubs From DISK='" + DropDownList1.SelectedValue + "'";
SqlConnection masConn = new SqlConnection("Server=.\SQLEXPRESS;Database=master;Integrated Security=True");
SqlCommand cmd = new SqlCommand(sql, masConn);
masConn.Open();
int a=cmd.ExecuteNonQuery();
if (a == -1)
{
Response.Write("success!");
}
else
{
Response.Write("fail!");
}
masConn.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
File.Delete(DropDownList1.SelectedValue);
BindFileName();
}
}