4

In my winform project I have a connection string to connect to SQL. I have this connection in app.config file like this;

 <connectionStrings>
  <add name="MyConnectionString" providerName="System.Data.SqlClient"
        connectionString="Server=(localdb)\\v11.0; Integrated Security=true; AttachDbFileName=C:\\Folder\\mydataBaseName.mdf;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" 
   />

and I get the connection:

string config = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
//and then
 using (SqlConnection conexao = new SqlConnection(config))
        {
            conexao.Open();
         .......
         .......
        }

When I run the app I get an error saying : "An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll"

But If I call the connection string directlly from code (not using the app.config) everthing is ok .

string config = "Server=(localdb)\\v11.0; Integrated Security=true; AttachDbFileName=C:\\Folder\\mydataBaseName.mdf;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";

Any ideias, how to solve the problem ?

Thanks Leonor

hi itsme
  • 431
  • 1
  • 9
  • 23
  • You need more information about the Exception - it will likely have a message that explains the problem, or wrap an `InnerException` that contains this detail. Did you check the `config` contains the string you expect? I suspect it doesn't and the issue is to do with the `ConfigurationManager`/app.config setup. – Charles Mager Jun 29 '14 at 11:21
  • can you put a debug point after the `config = ConfigurationManager...`, and see what's inside of your config to be sure it's ok? – Noctis Jun 29 '14 at 11:23
  • I just printed a message with the configurationString and it´s ok. – hi itsme Jun 29 '14 at 11:35
  • Which .NET framework version are you on? – Rahul Jun 29 '14 at 11:36
  • Details of the error: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 -Error..Database Runtime.Specified LocalDB instance name is invalid. ) – hi itsme Jun 29 '14 at 11:41
  • The target framework is - .Net framework 4 , an din my machine i have 4.5.1 – hi itsme Jun 29 '14 at 11:43
  • Is you `App.Config`file being copied to the binary location when built? – brainless coder Jun 29 '14 at 12:42

1 Answers1

8

In a C# non-verbatim string literal, \\ is used if you want to include a single backslash character in a string.

In other files, backslash is not necessarily a special character. In Web.config connection strings, you can include the backslash directly, without doubling it.

Or, in other words, the reason one connection string works and the other doesn't, is because you've really got two different connection strings.