如何删除无法识别的转义序列的错误 [英] How can remove the error coming unrecognized escape sequence

查看:102
本文介绍了如何删除无法识别的转义序列的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 SqlConnection con =  new  SqlConnection(ConfigurationManager.ConnectionStrings [  Data Source = .\SQLEXPRESS; AttachDbFilename = | DataDirectory | \Database.mdf; Integrated Security = True; User Instance = True]。ConnectionString); 





我的尝试:



< pre lang =c#> SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings [ Data Source = .\\SQLEXPRESS; AttachDbFilename = | DataDirectory | \\Database.mdf; Integrated Security = True; User Instance = True]。ConnectionString);

解决方案

在C#字符串中,反斜杠字符是一个特殊字符,它引入了转义序列,如双引号,换行符等。如果你想在字符串中使用反斜杠字符,有两种方法。

1)使用反斜杠的转义序列:'\\':

< pre lang =c#> string str = D :\\Temp \\;



2)在字符串前加上atsign,关闭转义序列:

  string  str =  @  D:\Temp \; 

在第二种情况下,要插入双引号字符,请使用两个双引号:

< pre lang =c#> string str = @ John说Hello;

'\ S'不是可识别的转义序列,因此您收到此错误消息。



但是......正如NotPoliticallyCorrect所说:你为什么要读书使用连接字符串从配置文件中获取连接字符串?

通常,您将使用:

  using (SqlConnection con =  new  SqlConnection(ConfigurationManager.ConnectionStrings [ < span class =code-string> MyDB]。ConnectionString))
{
...
}


SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"].ConnectionString);



What I have tried:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"].ConnectionString);

解决方案

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: '\\':

string str = "D:\\Temp\\";


2) Preface the string with an atsign, which turns off escape sequences:

string str = @"D:\Temp\";

In the second case, to insert a doublke quote character you use two doublequotes:

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:

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
   {
   ...
   }


这篇关于如何删除无法识别的转义序列的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆