I am building a C# application with SQL Server 2008 R2 database which is stored in the bin folder of my project. I use Linq to Sql method to create the database and attach it to my project.
The problem that I'm having is that when I'm trying to create a backup of my database. It throws an error saying
Database (database_name) does not exist make sure the name is entered correctly. BACKUP DATABASE is terminating abnormally.
Here is the code that i write on my button click event:
try
{
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "SQL Server database backup files|*.bak";
sd.Title = "Create Database Backup";
if (sd.ShowDialog() == DialogResult.OK)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string sqlStmt=string.Format("BACKUP DATABASE <database_name> TO DISK='{0}'",sd.FileName);
using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
conn.Open();
bu2.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Backup Created Sucessfully");
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
My Connection String:
string connStr = ConfigurationManager.ConnectionStrings["project_name.Properties.Settings.project_nameConnectionString"].ConnectionString;
and then from my app.config file
<add name="project_name.Properties.Settings.project_nameConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\database_name.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
so if any one have a solution to my problem that will be helpful.
AttachDbFileName=approach in your connection string, you cannot useBACKUP DATABASEsince that database file is not really attached to the SQL Server Express instance. That's one of the many drawbacks and shortcomings of that approach