【问题标题】:How do read connection string created by the settings file?如何读取设置文件创建的连接字符串?
【发布时间】:2012-05-24 05:51:23
【问题描述】:

当我刚刚有一个 app.config 时,每次我尝试 ConfigurationManager.AppSettings[0] 或 ConfigurationManager.AppSettings["keyName"] 时,我都会得到一个空值。所以我尝试使用 *.settings 文件,它为我创建了一个看起来像这样的 app.config

<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="IndexLoader.IndexLoader" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <applicationSettings>
    <IndexLoader.IndexLoader>
      <setting name="ConnectionString" serializeAs="String">
        <value>INITIAL CATALOG=xxx;DATA SOURCE=xxx;User ID=xxx;Password=xxx;Application Name=xxx;</value>
      </setting>
    </IndexLoader.IndexLoader>
  </applicationSettings>
</configuration>

现在如何使用 C# 读取此连接字符串?

该解决方案有多个项目,其中许多都有配置文件。有没有办法指定我希望使用代码项目中的配置文件?

【问题讨论】:

  • 使用 app.config 文件应该很简单。以防万一.. app.config 文件在输出文件夹上吗?并不是说您应该手动做一些事情来实现这一点,而是让我们从基本的开始。您能否也粘贴您访问该属性的方式以及该属性如何存储在 app.config 中?
  • 配置文件确实进入了名为 IndexLoader.dll.config 的 bin。我的问题中显示了属性如何存储在配置中。我不确定如何读取名称为 ConnectionString 的设置。

标签: c# config windows-console


【解决方案1】:

applicationSettings 不是appSettings。 要阅读 applicationSettings 中的条目,请使用

string myCnStr = Properties.Settings.Default.ConnectionString;

你的情况是

string myCnStr =IndexLoader.IndexLoader.Default.ConnectionString;

但是,ConnectionString 在 app.config 中有一个专门的部分,应该存储在那里 并从 ConfigurationManager.ConnectionStrings 集合中读取

See here 供参考

【讨论】:

  • 代码无法识别属性。属性的命名空间是什么?
  • 在你的情况下它可能是 IndexLoader.IndexLoader.ConnectionString
  • 您是否对 IndexLoader.IndexLoader.ConnectionString 的正确性进行了某种编辑大战?
  • @oers 真的不知道,我只是在最后加了一个分号。但是,我正在等待对此有最后决定权的 OP。它在上面的最后一条评论与最后一次提议的编辑不同。等待......
猜你喜欢
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
相关资源
最近更新 更多