如何读取/写入此app.config设置?

时间:2013-04-09 11:26:40

标签: c# .net-3.5 app-config

拥有以下app.config:

<configuration>
  <configSections>
    <sectionGroup name="businessObjects">
      <sectionGroup name="crystalReports">
        <section name="crystalReportViewer" type="System.Configuration.NameValueSectionHandler" />
      </sectionGroup>
    </sectionGroup>
  </configSections>

  <businessObjects>
    <crystalReports>
      <crystalReportViewer>
        <add key="maxNumberListOfValues" value="5000"/>
      </crystalReportViewer>
    </crystalReports>
  </businessObjects>

您将如何阅读以及如何在运行时设置 maxNumberListOfValues 设置?另外,如果app.config不存在怎么办?你如何在运行时以dinamically方式设置设置呢?

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码来获取要编辑的app.config文件..

Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

同样检查它是否为空可以使用

之类的东西
            //Check
            if (ConfigurationManager.AppSettings.AllKeys.Contains(str someKey))
            {
                if (configFile.AppSettings.Settings[str someKey].Value == string.Empty)
                    return true;
            }
            else
            {
                // If app config does not contain needed Keys
                //Handle issue
            }

但是,大概是app.config文件只读取值。如果要在运行时编辑它,请使用用户配置文件。在visual studio中,项目的settings.Settings文件夹中有一个名为properties的文件。使用此文件。

答案 1 :(得分:0)

app.config中的整个设置点是,如果你愿意,它们是静态的常量变量。他们不应该被改变。

这样的答案解释了从App Config中读取变量:Reading settings from App.Config

如果您没有app.config,则只需将maxNumberListOfValues设置为解决方案中的全局变量,例如,所有表单/页面都继承自的基本文件。

相关问题