【问题标题】:How to read/write this app.config setting?如何读/写这个 app.config 设置?
【发布时间】:2013-04-09 11:26:40
【问题描述】:

有以下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>

您将如何阅读以及如何在运行时设置 ma​​xNumberListOfValues 设置?另外,如果 app.config 不存在怎么办?那么,您将如何在运行时动态设置设置?

【问题讨论】:

  • 它是一个使用 Crystal Reports 运行时而不是我们的应用程序的变量,问题是它们没有显示任何其他设置其值的方式...这就是为什么我想知道如何更改它运行时的变量值...

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


【解决方案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 中,项目的 properties 文件夹中有一个名为 settings.Settings 的文件。使用它。

【讨论】:

  • 它是一个使用 Crystal Reports 运行时而不是我们的应用程序的变量,问题是它们没有显示任何其他设置其值的方式...这就是为什么我想知道如何更改它运行时的变量值...
  • @ase69s 使用 settings.Settings 文件。您可以将变量定义为user scope 属性并在运行时更改或读取它。
【解决方案2】:

app.config 中设置的全部意义在于它们是静态的常量变量,如果你愿意的话。它们不应该被改变。

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

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

【讨论】:

  • 不完全正确。可以在 ConfigurationSections 中修改和保存应用程序设置。为此使用全局变量不是一个好习惯。
  • 它是一个使用 Crystal Reports 运行时而不是我们的应用程序的变量,问题是它们没有显示任何其他设置其值的方式...这就是为什么我想知道如何更改它运行时的变量值...
  • 同意@Sani Huttunen,但我不会即时修改 ConfigurationSections。
猜你喜欢
  • 2010-10-26
  • 2011-05-12
  • 1970-01-01
  • 2012-03-01
  • 2011-04-08
  • 2013-01-09
  • 1970-01-01
  • 2013-05-10
  • 2018-04-07
相关资源
最近更新 更多