【问题标题】:Fetching connection string from appconfig file in c#从 C# 中的应用程序配置文件中获取连接字符串
【发布时间】:2012-01-26 14:34:24
【问题描述】:

我在app.config 文件中声明了以下连接字符串:

  <connectionStrings>
    <add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
  </connectionStrings>

当我尝试使用以下 C# 代码 sn-p 获取此连接字符串时,我得到了值 null。我无法获取连接字符串。语法有什么问题吗?

第一次尝试:

var settings = ConfigurationManager.ConnectionStrings["SqlConnectionString"];
string result = settings.ConnectionString;

第二次尝试:

string result = ConfigurationSettings.AppSettings["SqlConnectionString"];

【问题讨论】:

  • 您确定在您正在运行的程序集旁边部署了一个名为MyApp.exe.config 并且包含该连接字符串的文件吗?你在使用 NUnit 吗?从 VS 运行时,NUnit 似乎需要将 app.config 放在与正常不同的位置。如果您使用的是 asp.net Web 项目,您可能需要将连接字符串放在 web.config 文件中,而不是 app.config 文件中...
  • 第一个语法是从&lt;connectionStrings&gt; 部分获取值的正确语法。第二个肯定行不通。
  • 不,它不是 web 项目,它的平面 c# 项目

标签: c# visual-studio-2010 app-config


【解决方案1】:

首先,你必须添加appSettings标签

 <connectionStrings>
    <appSettings>
      <add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
    </appSettings>
  </connectionStrings>

其次,在您的项目中添加对System.Configuration 的引用,并在源代码中插入using System.Configuration

然后,您可以使用ConfigurationManager.AppSettings 访问您的配置设置:

string result = ConfigurationSettings.AppSettings["SqlConnectionString"];

【讨论】:

  • 这是我能找到的在 .Net 4.5 控制台应用程序中获取设置的唯一方法
  • 我在 Visual Studio 2008 中尝试此操作并收到错误消息“ConnectionString has invalid child element "appSettings"
  • 过时的方法.. 改用 ConfigurationManager.AppSettings["SqlConnectionString"]。注意:连接必须直接在 appSettings 部分(由于某些原因不理想)。
【解决方案2】:

对于非 Web 项目,并且在 OP 中设置 app.config,我通常会这样做,因为在编译应用程序时配置文件会更改名称(到 yourapp.exe.config):

    public static Configuration ExeConfig()
    {
        Assembly service = Assembly.GetAssembly(typeof(YourClass));
        return ConfigurationManager.OpenExeConfiguration(service.Location);
    }

然后引用第s个连接字符串:

ExeConfig().ConnectionStrings.ConnectionStrings[s].ConnectionString

【讨论】:

  • 如果你在图书馆或其他地方有这个,你似乎希望这是初始程序集的名称,那么你似乎想使用 Assembly.GetEntryAssembly ()
  • 您可以使用 Assembly.GetExecutingAssembly() 代替 Assembly.GetAssembly(typeof(YourClass)) - YourClass 令人困惑(哪个类?)。
【解决方案3】:

我有同样的问题,但经过大量研究,我发现代码抛出空引用异常的原因是因为如果你使用 connectionString 名称,它将返回空,当你尝试调用 ToString()ConfigurationManager.ConnectionStrings 属性的 ConnectionString 属性,即抛出异常时,
返回正确的连接字符串,您必须使用以下代码对 ConnectionStringSettings 进行索引。

ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings[/* index */];

string conString = conSettings.ConnectionString;

【讨论】:

    【解决方案4】:

    我这样做是为了获取我的连接字符串“OracleDbContext”...

    ConfigurationManager.ConnectionStrings["OracleDbContext"].ConnectionString;
    

    我的 web.config 看起来像:

      <connectionStrings>
        <add name="OracleDbContext" 
             providerName="Oracle.ManagedDataAccess.Client" 
             connectionString="User Id=oracle_user;              
                               Password=oracle_user_password;
                               Data Source=oracle" />
      </connectionStrings>
    

    【讨论】:

      【解决方案5】:

      我在 VS 2013 中编译 WinForm App 时注意到的一件事:

      我在我的设置文件中添加连接字符串 - 这会更新我的 app.config 文件

      当我期望时:

      var connectionString = ConfigurationManager.ConnectionStrings["theConnectionStringName"].ConnectionString;
      

      我必须写:

      var connectionString = ConfigurationManager.ConnectionStrings["MyAppNameSpace.Properties.Settings.theConnectionStringName"].ConnectionString;
      

      一切照旧

      【讨论】:

        【解决方案6】:
        <configuration>
          <appSettings>
           <add key="ConnectionString" value="blah blah blah"/>  </appSettings>
          </configuration>
        

        上述配置是否适用于以下 API/代码:

        string str = ConfigurationSettings.AppSettings["SqlConnectionString"];
        

        【讨论】:

          【解决方案7】:

          第一个语法肯定是有效的。

          可能的原因是应用程序中没有正确加载配置文件。我想确定它是什么类型的项目。如果是 WinForm 应用程序或 Console 应用程序,则需要在 app.config 中进行设置。它将被编译为 .config 并在应用程序启动时加载。如果是 Web 应用程序,恐怕不能将节点添加到 app.config,因为它不会被加载。您需要将它放在 web.config 中。此外,如果您想将设置与 .net 库 (DLL) 一起放在配置文件中,无论如何都不会加载配置文件。配置文件只会跟随主应用程序。

          【讨论】:

          • 如何发现这个错误?如果你在 VS 中调试代码,请确认 .vshost.exe.config 确实存在。 VS debug 会使用这个配置文件。
          【解决方案8】:

          另一个可能的失败原因可能是 .NET 框架的名称解析不正确。

          如果应用程序名称长于 8.3 名称(例如 GreatStuff.exe),它可能会使用其短的 8.3 等效名称(在我的示例中为 GREATS~1.EXE)启动,然后 .NET 将查找 app.config 文件只需将 .config 附加到短名称即可。这将失败。

          【讨论】:

            【解决方案9】:

            同样的问题。基于 Merlyn Morgan-Graham 和 Edward Zhu cmets,我重建了我的项目,该项目使用 app.config 创建了一个带有连接字符串的 myapp.exe.config 文件。原来的第一个语法然后就起作用了。

            其他问题:尝试使用项目属性对话框修改连接字符串,并将“project.My.Mysettings.”添加到连接字符串名称。导致失败。

            【讨论】:

              【解决方案10】:

              对于控制台应用还有另一种方法:

                  <configuration>
                <appSettings>
                  <add key="SqlConString" value="some connection string"/>
                </appSettings>
              

              阅读它

              using System.Configuration;
              

              然后使用

              string CONSTRING;
              AppSettingsReader ap = new AppSettingsReader();
              CONSTRING = ap.GetValue("SqlConString",typeof(string)).ToString();
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2015-03-02
                • 2022-12-11
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2020-05-01
                • 1970-01-01
                • 2013-04-15
                相关资源
                最近更新 更多