Click here to Skip to main content
15,880,132 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am creating a windows application.using sql server 2008. I am getting connection string problem while connecting to .mdf file which is in this location c\folder\file.mdf. 
what I did will explain you will get clear pucture.
first of all what I did is I have created 1 database in the sql with the tables. now I de-attached it. from c:\program files\sql server\data\mydb.mdf&mydblog.ldf, I copied in desktop. now from my application when ever I am entering a text and then click create button event it ic creating a texbox1.text.mdf and textbox1log.ldf. now I want to connect to this created database file.

I have give like this connection string but it is giving me connection is aborted and so on. SqlConnection con = new SqlConnection(@"Data Source=.\SQLExpress;Integrated security=true;AttachDbFilename=c:\maq\" + textbox1.Text + ".mdf;Trusted_Connection=Yes");

Help me for this I did this using .mdb it is successful but sql giving me trouble. I am new to use sql if I did any mistake please let me know I want learn a lot.
Kornfeld Eliyahu Peter 14-Jan-14 3:22am    
What the error you got?
hussain548 14-Jan-14 3:26am    
could not open new database'c:\maq\textbox1.text.mdf' create database is aborted
an attempt toattach-an auto named database file c:\maq\textbox1.text.mdf' failed and so on.

1 solution

Try this :
SqlConnection con = new SqlConnection("Data Source=.\\SQLExpress;Integrated security=true;AttachDbFilename=\"c:\\maq\\" + textbox1.Text + "\".mdf;Trusted_Connection=Yes");
Share this answer
hussain548 14-Jan-14 3:41am    
"un-recognized escape sequence"
while compiling. it is showing that error is at .\sqlexpress
hussain548 14-Jan-14 3:47am    
if I use like this it is giving me this runtime error
SqlConnection con = new SqlConnection(@"Data Source=.\SQLExpress;Integrated security=true;AttachDbFilename=\C:\maq\" + newmarketname.Text + "\".mdf;Trusted_Connection=Yes");

an attempt toattach-an auto named database file c:\maq\textbox1.text.mdf' failed and a database with the same name exists, or specified file can not be opened, or it is located on UNC share.

the database is exists only one time. so y I am getting this error.
Mehdi Gholam 14-Jan-14 3:59am    
Sorry I missed a slash, I have updated the solution.
hussain548 14-Jan-14 4:07am    
no issues sir, I appreciate for your help.
now after updating string as you said "Format of initialization string does notconform to specific starting at index 50"
this error getting sir.

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