【问题标题】:Reading App.config elements in a C# project在 C# 项目中读取 App.config 元素
【发布时间】:2014-03-23 18:08:52
【问题描述】:

我在 Visual Studio 2010 中工作。我在解决方案中有一个 C# 项目,在主项目目录中有一个 App.config。我正在尝试通过Main() 方法读取App.config 中的属性,如下所示:

String test = ConfigurationManager.AppSettings["streamType"];

我的 App.config 文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings"
              type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="InteropClient.Properties.Settings"
                type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                requirePermission="false" />
    </sectionGroup>
    <section name="connections" type="" />
    <section name="streamType" type="" />
    <section name="messageClass" type="" />
    <section name="serializationMethod" type="" />
    <section name="encryptionMethod" type="" />
  </configSections>

  <connections>
    <connection type="zkClient" connectionString="168.72.70.62:9181" sessionTimeout="5000" initInstructions="" name="zk1"
              classes="Sodao.Zookeeper.Config.ZookeeperConfig, Zookeeper" />
    <connection type="TcpClient" connectionString="" initInstructions="" />
  </connections>
  <streamType>MemoryStream</streamType>
  <messageClass>XGenericMessage</messageClass>
  <serializationMethod>Thrift</serializationMethod>
  <encryptionMethod></encryptionMethod>
</configuration>

试图运行 Main() 方法,上面的 C# 行抛出了一个 ConfigurationErrorsException

配置系统初始化失败。

我不知道为什么会这样。我想我已经完成了说明中的所有内容。我希望能澄清一下这个问题。

【问题讨论】:

    标签: c# app-config configurationmanager


    【解决方案1】:

    我相信它应该是这样的。

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
      </configSections>
      **<appSettings>
          <add key="streamType" value="Somevalue" />
      </appSettings>**
    </configuration>
    

    您的 AppSettings 节点位于 configSections 之外。

    【讨论】:

      【解决方案2】:

      这就是您使用 AppSettings 的方式:

      <appSettings>
        <add key="streamType" value="Somevalue" />
      </appSettings>
      

      【讨论】:

        【解决方案3】:

        你没有设置你想要的部分的类型..

        <section name="streamType" type="" />
        

        你应该为初始化添加这个部分

        【讨论】:

        • 用 type="MemoryStream" 填充它。
        猜你喜欢
        • 2014-04-19
        • 2011-05-15
        • 2023-03-03
        • 2018-12-11
        • 2018-07-17
        • 2012-09-05
        • 2012-04-09
        • 1970-01-01
        • 2012-07-31
        相关资源
        最近更新 更多