AppSettings 与 applicationSettings (.NET app.config / Web.config) 的优缺点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/460935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 11:02:17  来源:igfitidea点击:

Pros and cons of AppSettings vs applicationSettings (.NET app.config / Web.config)

.netweb-configapp-config

提问by Jader Dias

When developing a .NET Windows Forms Application we have the choice between those App.configtags to store our configuration values. Which one is better?

在开发 .NET Windows 窗体应用程序时,我们可以在这些App.config标记之间进行选择来存储我们的配置值。哪一个更好?

<configuration>

  <!-- Choice 1 -->
  <appSettings>
    <add key="RequestTimeoutInMilliseconds" value="10000"/>
  </appSettings>

  <!-- Choice 2 -->
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" >
        <section name="Project1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <applicationSettings>
    <Project1.Properties.Settings>
      <setting name="TABLEA" serializeAs="String">
        <value>TABLEA</value>
      </setting>
    </Project1.Properties.Settings>
  </applicationSettings>

</configuration>

采纳答案by marc_s

The basic <appSettings>is easier to deal with - just slap in a <add key="...." value="..." />entry and you're done.

基本<appSettings>的更容易处理 - 只需<add key="...." value="..." />输入一个条目即可完成。

The downside is: there's no type-checking, e.g. you cannot safely assume your number that you wanted to configure there really is a number - someone could put a string into that setting..... you just access it as ConfigurationManager["(key)"]and then it's up to you to know what you're dealing with.

缺点是:没有类型检查,例如您不能安全地假设您想要配置的号码确实有一个号码 - 有人可以将一个字符串放入该设置中.....您只需访问它ConfigurationManager["(key)"]然后它就可以了让你知道你在处理什么。

Also, over time, the <appSettings>can get rather convoluted and messy, if lots of parts of your app start putting stuff in there (remember the old windows.ini file? :-)).

此外,随着时间的推移,<appSettings>如果您的应用程序的许多部分开始将内容放入其中(还记得旧的 windows.ini 文件吗?:-)),它会变得相当复杂和混乱。

If you can, I would prefer and recommend using your own configuration sections - with .NET 2.0, it's really become quite easy, That way, you can:

如果可以,我更愿意并推荐使用您自己的配置部分 - 使用 .NET 2.0,它真的变得非常简单,这样,您可以:

  • a) Define your configuration settings in code and have them type-safe and checked
  • b) You can cleanly separate YOURsettings from everyone else's. And you can reuse your config code, too!
  • a) 在代码中定义您的配置设置,并使它们类型安全并经过检查
  • b) 您可以将您的设置与其他人的设置完全分开。你也可以重用你的配置代码!

There's a series of really good articles on you to demystify the .NET 2.0 configuration system on CodeProject:

在 CodeProject 上有一系列非常好的文章来揭开 .NET 2.0 配置系统的神秘面纱:

  1. Unraveling the mysteries of .NET 2.0 configuration

  2. Decoding the mysteries of .NET 2.0 configuration

  3. Cracking the mysteries of .NET 2.0 configuration

  1. 解开 .NET 2.0 配置的奥秘

  2. 解开 .NET 2.0 配置的奥秘

  3. 破解 .NET 2.0 配置的奥秘

Highly recommended! Jon Rista did a great job explaining the configuration system in .NET 2.0.

强烈推荐!Jon Rista 出色地解释了 .NET 2.0 中的配置系统。

回答by Peter C

Application settings can be controlled from a designer (there is usually a Settings.settings file by default) so its easier to modify and you can access them programmatically through the Settings class where they appear like a strongly typed property. You can also have application and user level settings, as well as default settings for rolling back.

应用程序设置可以由设计器控制(默认情况下通常有一个 Settings.settings 文件),因此它更容易修改,您可以通过 Settings 类以编程方式访问它们,它们看起来像强类型属性。您还可以拥有应用程序和用户级别设置,以及用于回滚的默认设置。

This is available from .NET 2.0 onwards and deprecates the other way of doing it (as far as I can tell).

这可以从 .NET 2.0 开始使用,并弃用了其他方式(据我所知)。

More detail is given at: msdn.microsoft.com/en-us/library/k4s6c3a0.aspx

更多详细信息见:msdn.microsoft.com/en-us/library/k4s6c3a0.aspx

回答by HAL9000

I've been using a pattern I found a while back where you use basic xml tags but wrap the settings in a static config class. So - a DIY App.Settings.

我一直在使用我不久前发现的一种模式,您使用基本的 xml 标签但将设置包装在静态配置类中。所以 - 一个 DIY App.Settings。

DotNetPearls Static Config Pattern

DotNetPearls 静态配置模式

If you do it this way you can:

如果你这样做,你可以:

  • use different sets of config values for different environments (dev, test, prod)
  • provide for sensible defaults for each setting
  • control how values are defined and instantiated
  • 为不同的环境(开发、测试、生产)使用不同的配置值集
  • 为每个设置提供合理的默认值
  • 控制如何定义和实例化值

It's tedious to set up but performs well, hides references to key names, and is strongly typed. This kind of pattern works well for config that isn't changed by the application, although you could probably work in support for changes as well.

设置起来很乏味,但性能很好,隐藏了对键名的引用,并且是强类型的。这种模式适用于应用程序未更改的配置,尽管您可能也可以支持更改。

Config:

配置:

<add key="machineName" value="Prod" />
<add key="anotherMachineName" value="Test" />
<add key="EnvTypeDefault" value="Dev" />

<add key="RootURLProd" value="http://domain.com/app/" />
<add key="RootURLTest" value="http://test.domain.com/app/" />
<add key="RootURLDev" value="http://localhost/app/" />

<add key="HumanReadableEnvTypeProd" value="" />
<add key="HumanReadableEnvTypeTest" value="Test Mode" />
<add key="HumanReadableEnvTypeDev" value="Development Mode" />

Config class:

配置类:

using System;
using System.Collections.Generic;
using System.Web;
using WebConfig = System.Web.Configuration.WebConfigurationManager;

    public static class Config
    {
        #region Properties

        public static string EnvironmentType { get; private set; }

        public static Uri RootURL { get; private set; }

        public static string HumanReadableEnvType { get; private set; }

        #endregion

        #region CTOR

        /// <summary>
        /// Initializes all settings when the app spins up
        /// </summary>
        static Config()
        {
            // Init all settings here to prevent repeated NameValueCollection lookups
            // Can increase performance on high volume apps

            EnvironmentType =
                WebConfig.AppSettings[System.Environment.MachineName] ??
                "Dev";

            RootURL =
                new Uri(WebConfig.AppSettings["RootURL" + EnvironmentType]);

            HumanReadableEnvType =
                WebConfig.AppSettings["HumanReadableEnvType" + Config.EnvironmentType] ??
                string.Empty;
        }

        #endregion
    }

回答by Matt

To understand the prosand consof settings in the app.config, I suggest that you look into the technical details of both. I have included links where you can find source code for handling, describing more technical details below.

要了解优点缺点的设置app.config,我建议你看看双方的技术细节。我已经包含了一些链接,您可以在其中找到处理的源代码,在下面描述了更多的技术细节。

Let me briefly summarize what I recognized when I worked with them (note:the same is applicable to the web.configfile of a web site / web application):

让我简要总结一下我在与他们合作时的认识(注意:这同样适用于web.config网站/网络应用程序的文件):



applicationSettings in .NET
(click above to view source code and technical details)

.NET 中的 applicationSettings
(点击上方查看源代码和技术细节)


Pros


优点

  • They allow to store typed data, including object types (via serializeAsproperty)

  • They have a user and application scope, allowing to store default values

  • They are supported in Visual Studio's configuration section

  • Long strings and/or data with special characters are very well supported (for example, embedded JSON strings containing double quotes)

  • 它们允许存储类型化数据,包括对象类型(通过serializeAs属性)

  • 它们有用户和应用程序范围,允许存储默认值

  • Visual Studio 的配置部分支持它们

  • 长字符串和/或带有特殊字符的数据得到很好的支持(例如,包含双引号的嵌入式 JSON 字符串)


Cons


缺点

  • User settings are stored in a different place in the user profile (with a cryptic path), can be difficult to clean up

  • Application scope settings are read-only during runtime of the application (only user scope settings can be changed during runtime)

  • Read / Write methods code built by Visual Studio's settings designer, not directly provided by 3rd party tools (see link above for a workaround solution)

  • 用户设置存储在用户配置文件中的不同位置(带有神秘路径),可能难以清理

  • 应用程序范围设置在应用程序运行期间是只读的(在运行期间只能更改用户范围设置)

  • 由 Visual Studio 的设置设计器构建的读取/写入方法代码,而不是由 3rd 方工具直接提供(请参阅上面的链接以获取解决方法)



AppSettings in .NET
Update:AppSettings in .NET Core
(click above to view source code and technical details)

.NET
更新中的AppSettings .NET Core 中的 AppSettings
(点击上方查看源代码和技术细节)


Pros


优点

  • Are "light-weight", i.e. easy to handle

  • Read and write access during runtime of the application

  • They can be edited easily by Administrators in the
    Internet Information Services (IIS) Manager
    (Features View -> Application Settings, note that the name of the icon is misleading since it can only handle AppSettings and not ApplicationSettings)

  • 是“轻量级的”,即易于处理

  • 应用程序运行期间的读写访问

  • 管理员可以在
    Internet 信息服务 (IIS) 管理器中轻松编辑它们
    (功能视图 -> 应用程序设置,请注意图标的名称具有误导性,因为它只能处理 AppSettings 而不能处理 ApplicationSettings)


Cons


缺点

  • Support only string data; string length and special characters are limited

  • They don't have a user scope

  • They don't support default values

  • Are not directly supported in Visual Studio's configuration section

  • 仅支持字符串数据;字符串长度和特殊字符有限制

  • 他们没有用户范围

  • 他们不支持默认值

  • Visual Studio 的配置部分不直接支持



回答by Drew Noakes

I like working with the simpler version for storing and accessing single values.

我喜欢使用更简单的版本来存储和访问单个值。

<appSettings>
    <add key="MyConfigKey" value="true"/>
</appSettings>

I wrote a utility class to access values in a typesafe way that allows for default values. If defaults are not provided, then helpful exception messages are given.

我编写了一个实用程序类,以允许默认值的类型安全方式访问值。如果未提供默认值,则会给出有用的异常消息。

You can see/download the class here:

您可以在此处查看/下载课程:

http://www.drewnoakes.com/code/util/app-settings-util/

http://www.drewnoakes.com/code/util/app-settings-util/