我想用C#创建我的数据库的备份。当我单击更新按钮时,它会正确显示在“保存文件”对话框中,但不会创建备份。 save
单击后,它显示错误"error in catch"
。这是我的代码:
string connection = @"data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\personal_accounting.mdf;integrated security=True;";
using (SqlConnection con = new SqlConnection(connection))
{
ServerConnection srvConn = new ServerConnection(con);
Server srvr = new Server(srvConn);
if (srvr != null)
{
try
{
Backup backupdb = new Backup();
backupdb.Action = BackupActionType.Database;
backupdb.Database = "personal_accounting";
Microsoft.Win32.SaveFileDialog savefd = new Microsoft.Win32.SaveFileDialog();
//SaveFileDialog savefd = new SaveFileDialog();
savefd.Filter = "Backup File (*.Bak)|*.Bak";
savefd.FileName = DateTime.Now.ToString("yyyyMMdd_HHmmss");
Nullable<bool> result = savefd.ShowDialog();
if (result==true)
{
//System.Windows.MessageBox.Show("ok");
BackupDeviceItem bkpDevice = new BackupDeviceItem(savefd.FileName, DeviceType.File);
backupdb.Devices.Add(bkpDevice);
backupdb.SqlBackup(srvr);
//--------------------------------- This Will Show Message box -----------------
msgnotic = new NotifyMessageManager
(
Screen.Width,
Screen.Height,
200,
150
);
msgnotic.Start();
NotifyMessage msg = null;
msg = new NotifyMessage("img/GreenSkin.png", "message", "Backup has been created",
() =>
System.Windows.MessageBox.Show("operation done!", "message", MessageBoxButton.OK));
msgnotic.EnqueueMessage(msg);
//`-----------------------------End msgbox-------------------------------`
}
}
catch
{
System.Windows.MessageBox.Show("Error in save backup");
}
}
}
答案 0 :(得分:2)
您只需先显示“保存文件”对话框,然后检查DialogResult
是否正常,然后执行其余操作:
if(savefd.ShowDialog() == DialogResult.OK)
{
//do sql connection, backup creation and ... here
}