Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I used the code below to backup from SQLEXPRESS
C#
SqlConnection con = new SqlConnection(@"Data Source=.\SQLExpress;User                   Instance=true;Integrated Security=True;Initial Catalog=[myDb];AttachDBFilename='" + DbPath + "'");
SqlCommand com = new SqlCommand("BACKUP DATABASE [myDb] TO DISK = N'" + BackupPath + "'",con);
com.Connection.Open();
com.ExecuteNonQuery();
com.Connection.Close();

But I get this exception :
Database 'myDb' does not exist. Make sure that the name is entered correctly.
BACKUP DATABASE is terminating abnormally.

And when I change sqlconnection to this:
C#
SqlConnection con = new SqlConnection(@"Data Source=.\SQLExpress;User Instance=true;Integrated Security=True;Initial Catalog=[myDb];AttachDBFilename='" + DbPath + "';database=myDb");

I get this exception :
Unable to open the physical file "C:\Users\MohammadHG\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\bin\Debug\Database\db.mdf". Operating system error 32: "32(failed to retrieve text for this error. Reason: 15105)".
Cannot attach the file 'C:\Users\MohammadHG\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\bin\Debug\Database\db.mdf' as database 'myDb'.

I used to connect and execute SQLCommands allover my application without any problems, I just have problem with backup and restore.
please help me...
Posted
Updated 6-Oct-14 22:48pm
v2

1 solution

If you are trying to restore a database that does not exist then your connection string should not be connecting to it, try connecting to master instead.
C#
SqlConnection con = new SqlConnection(@"Data Source=.\SQLExpress;User Instance=true;Integrated Security=True;Initial Catalog=master");
 
Share this answer
 
Comments
MohammadHG 7-Oct-14 5:12am    
Hi Mehdi
Thanks for your answer.
First I want to create backup.
I used your sqlconnection and I get login failed exception:
Cannot open database "[master]" requested by the login. The login failed.
Mehdi Gholam 7-Oct-14 5:24am    
Your user account must have permission to the database you want to connect to also (generally an admin does the db restore).
MohammadHG 7-Oct-14 5:34am    
My user account is an administrator account. What is your suggestion?
In SQL Server I simple connect to my database and backup, restore it without any problems, but in SQLExpress I have this issue, how can I attach my db and backup, restore it as an administrator ?
Mehdi Gholam 7-Oct-14 5:40am    
Your account must be admin on SQLExpress.
MohammadHG 7-Oct-14 6:09am    
How can I check that?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900