app.Config中的ConnectionString无法工作。

4
在我的winform项目中,我有一个连接字符串来连接SQL。我在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" 
   />

我理解了这个连接:

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

当我运行应用程序时,出现了一个错误: "未处理的异常类型'System.Data.SqlClient.SqlException'在System.Data.dll中发生"

但如果我直接从代码调用连接字符串(而不使用app.config),一切都正常。

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

有什么想法可以解决这个问题?

谢谢,Leonor


你需要更多关于异常的信息 - 它很可能有一个解释问题的消息,或者包含这个细节的 InnerException。你检查了 config 是否包含你期望的字符串吗?我怀疑它没有,并且问题与 ConfigurationManager/app.config 的设置有关。 - Charles Mager
你能在 config = ConfigurationManager... 后面加一个调试断点,看看你的配置文件里面是不是正确的吗? - Noctis
我刚刚打印了一条带有configurationString的消息,一切正常。 - hi itsme
你使用的是哪个 .NET Framework 版本? - Rahul
在构建时,您的 App.Config 文件是否被复制到二进制位置? - brainless coder
显示剩余2条评论
1个回答

8
在C#非verbatim字符串字面量中,如果要在字符串中包含单个反斜杠字符,则使用\\
在其他文件中,反斜杠不一定是特殊字符。在Web.config连接字符串中,可以直接包含反斜杠,而无需将其加倍。
换句话说,一个连接字符串有效,而另一个无效的原因是你实际上有两个不同的连接字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接