Click here to Skip to main content
15,887,464 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"].ConnectionString);


What I have tried:

C#
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"].ConnectionString);
Posted
Updated 4-Apr-17 6:39am
v2
Comments
[no name] 4-Apr-17 12:26pm    
First of all, why are you trying to read a connection string from your config file by using a connection string? This makes no sense.
Bryian Tan 4-Apr-17 12:37pm    

1 solution

In C# strings, the backslash character is a "special" which introduces "escape sequences" like double quotes, newline, and so forth. If you want to use a backslash character in a string, there are two ways.
1) Use the escape sequence for backslash: '\\':
C#
string str = "D:\\Temp\\";

2) Preface the string with an atsign, which turns off escape sequences:
C#
string str = @"D:\Temp\";
In the second case, to insert a doublke quote character you use two doublequotes:
C#
string str = @"John said ""Hello""";
'\S' is not a recognised escape sequence, so you get this error message.

But ... as NotPoliticallyCorrect says: "why are you trying to read a connection string from your config file by using a connection string?"
Normally, you would use:
C#
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
   {
   ...
   }
 
Share this answer
 

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