I trying to make backup and restore as a start i am trying to get backup database so write a code like this
try
{
string cbdfilename = "c:\\Bbcon.bak";
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\BbCon.mdf;Integrated Security=True;Connect Timeout=30;");
string sql = "Backup database @DBNAME to Disk = @FILENAME with Format";
SqlConnection.ClearAllPools();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@DBNAME", "BbCon");
cmd.Parameters.AddWithValue("@FILENAME", cbdfilename);
con.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("Backup DB failed" + ex.ToString());
}
finally
{
con.Close();
con.Dispose();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
but when i run this code i get an error database BbCon not exist check your database i don't know what is problem for sure but i think i have given wrong path to database I know the path od database correctly it is like
C:\Users\Mahdi Rashidi\AppData\Local\Apps\2.0\NOL11TLW.9XG\CZM702AQ.LPP\basu..tion_939730333fb6fcc8_0001.0002_fd707bbb3c97f8d3
but this project is for some other clients so when i install this software to other computer path will change so i will get an error so i am begging you all to help finding me a better solution for creating a backup programattically
I recommend you to create an app.config file and put the backup target path there
OR
What I did some time ago (to load assemblies dynamically, but this piece of code allows u to retrieve the path location based on the assembly that you're running) it was something like:
(Don't forget to add System.Reflection to your using list)
// get the current assembly from cache
var currentAssembly = Assembly.GetEntryAssembly();
// if current assembly is null
if (currentAssembly == null)
{
// get the current assembly from stack trace
currentAssembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
}
// get the assemblies path (from returned assembly)
assembliesPath = Path.GetDirectoryName(currentAssembly.Location);
From that point now you can concatenate you "Data Path" and save your data there.
Hope it helps.