سلام دوست عزیز
این کد تهیه بک اپ و بازیابی هستش
2 تا باتن هست برای دیالوگ ذخیره دیتابیس و اونیکی هم گرفتن پشتیان
namespace BackupRestore
{
public partial class Form1 : Form
{
private string _connectionString = "Data Source=(local);Initial Catalog=DBName ;user id=sa";
private SqlConnection SqlConnection1 = new SqlConnection();
public Form1()
{
InitializeComponent();
this.SqlConnection1.ConnectionString = this._connectionString;
}
private void Backup(string filename)
{
try
{
string command = @"Backup DataBase DBName To Disk='" + filename + "'";
this.Cursor = Cursors.WaitCursor;
if (SqlConnection1.State != ConnectionState.Open)
{
SqlConnection1.Open();
}
SqlCommand SqlCommand1 = null;
SqlCommand1 = new SqlCommand(command, this.SqlConnection1);
SqlCommand1.ExecuteNonQuery();
this.Cursor = Cursors.Default;
MessageBox.Show("تهیه نسخه پشتیبان از اطلا عات با موفقیت انجام شد");
}
catch (Exception ex)
{
MessageBox.Show("Error : ", ex.Message);
}
}
///////////////restore
private void Restore(string filename)
{
try
{
string command = @"ALTER DATABASE DBName SET SINGLE_USER with ROLLBACK IMMEDIATE " + " USE master " + " RESTORE DATABASE DBName FROM DISK= N'" + filename + "'";
this.Cursor = Cursors.WaitCursor;
SqlCommand SqlCommand1 = null;
if (SqlConnection1.State != ConnectionState.Open)
{
SqlConnection1.Open();
}
SqlCommand1 = new SqlCommand(command, this.SqlConnection1);
SqlCommand1.ExecuteNonQuery();
this.Cursor = Cursors.Default;
MessageBox.Show("بازیابی اطلاعات از نسخه پشتیبان از با موفقیت انجام شد");
}
catch (Exception ex)
{
MessageBox.Show("Error : ", ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
string filename = string.Empty;
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.DefaultExt = "";
saveFileDialog1.Filter = @"SQL Backup Files ALL Files (*.*) |*.*| (*.Bak)|*.Bak";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.Title = "Backup SQL File";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
filename = saveFileDialog1.FileName;
Backup(filename);
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
string filename = string.Empty;
openFileDialog1.Filter = @"SQL Backup Files ALL Files (*.*) |*.*| (*.Bak)|*.Bak";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Filter = @"SQL Backup Files (*.*)|";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filename = openFileDialog1.FileName;
Restore(filename);
}
}