【问题标题】:ConnectionString in app.Config not workingapp.Config 中的 ConnectionString 不起作用
【发布时间】:2014-06-29 11:19:04
【问题描述】:

在我的 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";

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

感谢莱昂诺尔

【问题讨论】:

  • 您需要有关异常的更多信息 - 它可能会有解释问题的消息,或者包装包含此详细信息的 InnerException。您是否检查了 config 包含您期望的字符串?我怀疑它没有,问题与ConfigurationManager/app.config 设置有关。
  • 您能否在config = ConfigurationManager... 之后放置一个调试点,并查看配置中的内容以确保一切正常?
  • 我刚刚用 configurationString 打印了一条消息,没关系。
  • 您使用的是哪个 .NET 框架版本?
  • 错误详细信息:建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:SQL Network Interfaces,错误:50 -Error..Database Runtime.Specified LocalDB instance name is invalid.)

标签: c# sql connection-string


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2012-08-15
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 2011-04-08
    • 2013-03-19
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    相关资源
    最近更新 更多