این کد تو رنامه خودم بدون هیچ مشکلی اجرا میشه :
private void ToolStripMenuItemCreatBackUp_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.AddExtension = true;
saveFileDialog.CheckFileExists = false;
saveFileDialog.CheckPathExists = true;
saveFileDialog.OverwritePrompt = true;
saveFileDialog.DereferenceLinks = true;
saveFileDialog.FileName = "Backup";
saveFileDialog.Filter = "Backup File (*.Bak)|*.Bak";
saveFileDialog.DefaultExt = "Bak";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.InitialDirectory = "C:\\";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "BACKUP DATABASE MontazeriAbbasAbad TO DISK = @Destination WITH FORMAT";
sqlCommand.Parameters.Add("@Destination", SqlDbType.VarChar);
temp = saveFileDialog.FileName;
sqlCommand.Parameters["@Destination"].Value = saveFileDialog.FileName;
if (temp.StartsWith("C:\\"))
{
MessageBox.Show(" . ", telBookName);
saveFileDialog.ShowDialog();
}
else
{
sqlConnection.Open();
this.Cursor = Cursors.WaitCursor;
sqlCommand.ExecuteNonQuery();
MessageBox.Show(" ", telBookName);
}
}
}
catch (Exception)
{
MessageBox.Show(" ", telBookName);
}
}
Restore :
private void ToolStripMenuItemLoadBackUpFile_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
if ((openFileDialog1.FileName != "") && (openFileDialog1.FileName != "openFileDialog1"))
{
try
{
string filename = openFileDialog1.FileName;
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "ALTER DATABASE MontazeriAbbasAbad SET SINGLE_USER WITH ROLLBACK IMMEDIATE USE master;"
+ " RESTORE DATABASE MontazeriAbbasAbad FROM DISK =N'" + filename + "' WITH REPLACE ";
sqlCommand.Connection = sqlConnection;
sqlConnection.Open();
this.Cursor = Cursors.WaitCursor;
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = " ALTER DATABASE MontazeriAbbasAbad SET MULTI_USER ";
sqlCommand.ExecuteNonQuery();
MessageBox.Show(" ", telBookName);
}
catch
{
MessageBox.Show(" ", telBookName);
}
}
}