我试图在 C# WinForms 中备份和恢复我的数据库 .MDF 文件。我认为它是备份的,因为我看到了一个 .BAK 文件,但是当我恢复时,它不起作用。两者在运行时都没有错误,但我认为我的代码有问题。这是我的代码:
private void backupToolStripMenuItem1_Click(object sender, EventArgs e)
{
saveFileDialogBackUp.FileName = fileName;// +".bak";
saveFileDialogBackUp.Filter = "Backup File (*.bak)|*.bak";
saveFileDialogBackUp.Title = "File Location";
try
{
saveFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + @"Sauvegardes";
if (saveFileDialogBackUp.ShowDialog() == DialogResult.OK)
{
SqlCommand cmd = new SqlCommand(@"BACKUP DATABASE [dbCPS] TO DISK = '" +
saveFileDialogBackUp.FileName + ".bak' WITH NOFORMAT, NOINIT, NAME = +
N'dbCPS-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10 ", +
conn);
conn.Close();
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Backup Successful!", "CPS Backup", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch(Exception error)
{
MessageBox.Show(error.ToString());
}
}
private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialogBackUp.Filter = "Backup File (*.bak)|*.bak";
openFileDialogBackUp.FileName = "CPS";
openFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + @"Sauvegardes";
if (openFileDialogBackUp.ShowDialog() == DialogResult.OK)
{
//RestoreDatabase(conn, "dbCPS", openFileDialogBackUp.FileName);
using (SqlConnection connection = new SqlConnection(GlobalVar.connectionString))
{
using (SqlCommand command = new SqlCommand(@"RESTORE DATABASE dbCPS FROM DISK = '" + openFileDialogBackUp.FileName + @"' WITH RECOVERY, MOVE 'dbCPS' TO 'C:\Users\admin\Desktop\New backup\dbCPS.mdf', MOVE 'dbCPS_log' TO 'C:\Users\admin\Desktop\New backup\dbCPS_Log.ldf', REPLACE", connection))
{
connection.Open();
// Add the parameters for the SelectCommand.
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
MessageBox.Show("Database Restored", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
connection.Close();
}
}
}
}