1

i'm unable to connect to SQL server when i use connection string:

this code works well:

SqlConnection db_connection = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
db_connection.Open();

but if put this on Web.config:

  <connectionStrings>  
      <add name="conn" connectionString="Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" />  
  </connectionStrings>

Then on my page:

SqlConnection db_connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
db_connection.Open(); // fail - error 50

So it will only work if i don't use the configuration manager...

  • Have you tried printing out `ConfigurationManager.ConnectionStrings["conn"].ToString()` to see if it actually yields what you are looking for? – Tobias Tengler Dec 01 '18 at 17:17
  • i'm getting: "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" –  Dec 01 '18 at 17:30

2 Answers2

0

The issue was that the slashes between the server and the instance name were escaped for the code to interpret the string, but in the [app|web].config file, it understands there are going to be interesting characters in there, and handles them accordingly, and do not need the escaping that the code does.

Removing the double slash between the (localdb) and MSSQLLocalDB fixed the issue for me. Try the following in your connectionStrings config:

 <connectionStrings>  
     <add name="conn" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" />  
 </connectionStrings>
Nathan Werry
  • 876
  • 7
  • 18
  • 1
    @frenchman100 As an advice, you would like to get used to `@"c:\path\"` instead `"c:\\path\\"`. It will minimice having this problem again – Cleptus Dec 02 '18 at 09:25
-1

Hello try to use this and 1. in reference add System.Configuration 2. write in cs Using System.Configuration 3. var connectionString = ConfigurationManager.ConnectionStrings["conn"].ToString();

put this into config file