Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I am trying to attach exisitng database to SQL Server 2008.
When I use:
str = String.Format("EXEC sp_attach_db @dbname = '{0}',@filename1 = '{1}',@filename2 = '{2}'", databaseName, mdfFile, ldfFile);
com = new SqlCommand(str, myConn);

I get an error: Unable to open the physical file "C:\TestDB\MyProgram_Data.mdf". Operating system error 2: "2(error not found)".

What I have tried:

But when I use:
str = "EXEC sp_attach_db @dbname = N'MyProgram' ,@filename1 = N'C:\\TestDB\\MyProgram\\MyProgram_Data.mdf',@filename2 = N'C:\\TestDB\\MyProgram\\MyProgram_Log.ldf'";

Everything is OK.

Why I am not able to use string.Format()?
Posted
Updated 18-May-17 5:50am
Comments
CHill60 18-May-17 11:44am    
What are the values of databaseName, mdfFile and ldfFile? If they have the double backslashes \\ then it won't work.
If you put a breakpoint on com = new SqlCommand(str, myConn); does str contain exactly what you have in your string literal version?

So this works

C:\TestDB\MyProgram\MyProgram_Data.mdf


...and this doesn't

C:\TestDB\MyProgram_Data.mdf


Spot the difference?

"mdfFile" and "ldfFile" do not have the correct values that match where your database is.
 
Share this answer
 
Comments
stivanov 18-May-17 16:57pm    
Indeed :) Thanks
Because the path is wrong:
Unable to open the physical file "C:\TestDB\MyProgram_Data.mdf".
Doesn't work, but:
str = "EXEC sp_attach_db @dbname = N'MyProgram' ,@filename1 = N'C:\\TestDB\\MyProgram\\MyProgram_Data.mdf'
Does. It has an extra folder name in there: "MyProgram"
 
Share this answer
 
Comments
stivanov 18-May-17 16:57pm    
You are right. Thank you :)
OriginalGriff 18-May-17 17:11pm    
You're welcome!

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