I have developed a windows application with vs2010 and c#. I would like to know a way to backup and restore my local mdf database programmatically. With sdf database I use File Copy but it doesn't seem to work with mdf files. Can anyone help?
Asked
Active
Viewed 2,798 times
0

Toon Krijthe
- 52,876
- 38
- 145
- 202

MarcusV
- 355
- 3
- 6
- 19
-
Can you show us your connection string? I'm asking because I need to know whether you're using a database attached to the SQL Server (Express) instance (in which case: see Steve's perfect answer for this scenario), or whether you're using a "free-floating" `.mdf` file that's being attached only on demand – marc_s Jun 29 '12 at 18:32
-
sorry for the delay, i'm using a "free-floating" .mdf – MarcusV Jun 29 '12 at 21:54
-
here is my connection string: connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" – MarcusV Jun 29 '12 at 21:55
2 Answers
3
Try in this way:
- Go to Sql Management Studio and select the database you want to backup
- Right click and select 'Tasks' -> 'Backup'
- Adjust the parameters as you like, but don't confirm the dialog
- Press the button SCRIPT and dismiss the dialog
On the query window insert the following text before the backup command
CREATE PROCEDURE DO_BACKUP AS BEGIN -- HERE GOES THE BACKUP TEXT CREATED BY THE SCRIPT BUTTON -- FOR EXAMPLE BACKUP DATABASE [Customers] TO DISK = N'E:\backups\customers.bak' WITH NOFORMAT, NOINIT, NAME = N'Customers - Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10 END
and execute (selecting the correct database) using the exclamation mark button.
Now you have a stored procedure called DO_BACKUP that you can call from your code using the normal ADO.NET objects like SqlConnection
and SqlCommand
-
1That works - ***IF*** the database is attached to the SQL Server instance. From the question, I would almost assume the OP doesn't have the database attached to an instance - but as a "free-floating" `.mdf` file that gets attached to an user instance of SQL Server Express on demand. In that case, this approach doesn't work, unfortunately. – marc_s Jun 29 '12 at 18:31
-
Thanks @marc_s I always get lost when a bullet list is followed by code. – Steve Jun 29 '12 at 18:31
-
-
0
I struggled a lot with this, and the accepted answer does not do the trick, so here is a solution that worked for me (thanks to dnxit)
it may help someone.
Backup
try
{
var dlg = new System.Windows.Forms.FolderBrowserDialog();
var result = dlg.ShowDialog(this.GetIWin32Window());
if (result.ToString() == "OK")
{
var dbfileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LibraryManger.mdf");
var backupConn = new SqlConnection { ConnectionString = eb.GetConnectionString() };
backupConn.Open();
var backupcomm = backupConn.CreateCommand();
var backupdb = $@"BACKUP DATABASE ""{dbfileName}"" TO DISK='{Path.Combine(dlg.SelectedPath,"LibraryManagement.bak")}'";
var backupcreatecomm = new SqlCommand(backupdb, backupConn);
backupcreatecomm.ExecuteNonQuery();
backupConn.Close();
MessageBox.Show($"Database backup has successfully stored in {Path.Combine(dlg.SelectedPath, "LibraryManagement.bak")}", "Confirmation");
}
}
catch (Exception ex)
{
if(ex.Message.Contains("Operating system error"))
{
MessageBox.Show("Please chose a public folder.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
Restore
You'll have to close existing connection before you restore
try
{
if (eb != null)
{
eb.DisposeConnection();
eb = null;
}
var dlg = new OpenFileDialog();
dlg.InitialDirectory = "C:\\";
dlg.Filter = "Database file (*.bak)|*.bak";
dlg.RestoreDirectory = true;
if (Equals(dlg.ShowDialog(), true))
{
using (var con = new SqlConnection())
{
con.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
con.Open();
var dbfileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LibraryManger.mdf");
using (var cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = $@"RESTORE DATABASE ""{dbfileName}"" FROM DISK='{dlg.FileName}'";
cmd.ExecuteNonQuery();
}
con.Close();
}
MessageBox.Show($"Database backup has successfully restored.", "Confirmation");
eb = new EntityBroker.EntityBroker();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

Mugiwara Noshanks
- 39
- 1
- 9