简体   繁体   English

app.Config中的ConnectionString不起作用

[英]ConnectionString in app.Config not working

In my winform project I have a connection string to connect to SQL. 在我的winform项目中,我有一个连接到SQL的连接字符串。 I have this connection in app.config file like this; 我在app.config文件中有这样的连接;

 <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" 当我运行应用程序时,我收到一条错误消息:“System.Data.dll中发生了'System.Data.SqlClient.SqlException'类型的未处理异常”

But If I call the connection string directlly from code (not using the app.config) everthing is ok . 但是,如果我直接从代码中调用连接字符串(不使用app.config),那么就可以了。

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 谢谢Leonor

In a C# non-verbatim string literal, \\\\ is used if you want to include a single backslash character in a string. 在C#非逐字字符串文字中,如果要在字符串中包含单个反斜杠字符,则使用\\\\

In other files, backslash is not necessarily a special character. 在其他文件中,反斜杠不一定是特殊字符。 In Web.config connection strings, you can include the backslash directly, without doubling it. 在Web.config连接字符串中,您可以直接包含反斜杠,而不会加倍。

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. 或者,换句话说,一个连接字符串工作而另一个连接字符串不工作的原因是因为您确实有两个不同的连接字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM