gpt4 book ai didi

c# - app.Config 中的 ConnectionString 不起作用

转载 作者:太空狗 更新时间:2023-10-30 00:31:36 26 4
gpt4 key购买 nike

在我的 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.dll 中发生类型为‘System.Data.SqlClient.SqlException’的未处理异常”

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

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

任何想法,如何解决问题?

谢谢莱昂诺尔

最佳答案

在 C# 非逐字字符串文字中,如果要在字符串中包含单个反斜杠字符,则使用 \\

在其他文件中,反斜杠不一定是特殊字符。在 Web.config 连接字符串中,您可以直接包含反斜杠,而无需加倍。

或者,换句话说,一个连接字符串起作用而另一个不起作用的原因是因为您确实有两个不同的连接字符串。

关于c# - app.Config 中的 ConnectionString 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24475592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com