AppSettings与applicationSettings(。净app.config / web . config)

时间:2022-11-02 20:08:05

When developing a .NET Windows Forms Application we have the choice between those App.config tags 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>

5 个解决方案

#1


139  

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

基本的< appSettings >是容易处理,只是记耳光 <添加键=“....”价值=“……” />条目,你完成了。

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? :-)).

而且,随着时间的推移, 可能会变得相当复杂和混乱,如果应用程序的很多部分开始在其中放置东西(记住旧的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
  • a)在代码中定义配置设置,并让它们类型安全并进行检查
  • b) You can cleanly separate YOUR settings from everyone else's. And you can reuse your config code, too!
  • 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

    揭开。net 2.0配置的神秘面纱

  2. Decoding the mysteries of .NET 2.0 configuration

    解码。net 2.0配置的奥秘

  3. Cracking the mysteries of .NET 2.0 configuration

    破解。net 2.0配置的奥秘

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

强烈推荐!Jon Rista很好地解释了。net 2.0中的配置系统。

#2


18  

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.

应用程序设置可以从设计器控制(通常有一个设置)。设置文件默认)因此它更容易修改,您可以通过编程方式通过设置类访问它们,它们在其中显示为强类型属性。您还可以拥有应用程序和用户级设置,以及用于回滚的默认设置。

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

#3


12  

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应用程序。

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)
  • 为不同的环境使用不同的配置值集(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
    }

#4


9  

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/

#5


6  

To understand the pros and cons of 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.config file of a web site / web application):

让我简要地总结一下我在使用它们时所认识到的东西(注意:同样适用于web。web站点/ web应用程序的配置文件):


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

Pros

applicationSettings(单击上面查看源代码和技术细节)优点

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

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

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

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

  • They are supported in Visual Studio's configuration section

    它们在Visual Studio的配置部分中得到支持

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

    支持长字符串和/或具有特殊字符的数据(例如,包含双引号的嵌入式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的设置设计器构建的,而不是由第三方工具直接提供的(参见上面的链接解决方案)


AppSettings
(click above to view source code and technical details)

Pros

AppSettings(点击上面查看源代码和技术细节)优点

  • 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 Information Services (IIS) Manager中的管理员轻松编辑它们(Features View ->应用程序设置,注意图标的名称具有误导性,因为它只能处理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的配置部分中不直接支持吗


#1


139  

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

基本的< appSettings >是容易处理,只是记耳光 <添加键=“....”价值=“……” />条目,你完成了。

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? :-)).

而且,随着时间的推移, 可能会变得相当复杂和混乱,如果应用程序的很多部分开始在其中放置东西(记住旧的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
  • a)在代码中定义配置设置,并让它们类型安全并进行检查
  • b) You can cleanly separate YOUR settings from everyone else's. And you can reuse your config code, too!
  • 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

    揭开。net 2.0配置的神秘面纱

  2. Decoding the mysteries of .NET 2.0 configuration

    解码。net 2.0配置的奥秘

  3. Cracking the mysteries of .NET 2.0 configuration

    破解。net 2.0配置的奥秘

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

强烈推荐!Jon Rista很好地解释了。net 2.0中的配置系统。

#2


18  

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.

应用程序设置可以从设计器控制(通常有一个设置)。设置文件默认)因此它更容易修改,您可以通过编程方式通过设置类访问它们,它们在其中显示为强类型属性。您还可以拥有应用程序和用户级设置,以及用于回滚的默认设置。

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

#3


12  

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应用程序。

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)
  • 为不同的环境使用不同的配置值集(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
    }

#4


9  

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/

#5


6  

To understand the pros and cons of 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.config file of a web site / web application):

让我简要地总结一下我在使用它们时所认识到的东西(注意:同样适用于web。web站点/ web应用程序的配置文件):


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

Pros

applicationSettings(单击上面查看源代码和技术细节)优点

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

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

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

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

  • They are supported in Visual Studio's configuration section

    它们在Visual Studio的配置部分中得到支持

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

    支持长字符串和/或具有特殊字符的数据(例如,包含双引号的嵌入式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的设置设计器构建的,而不是由第三方工具直接提供的(参见上面的链接解决方案)


AppSettings
(click above to view source code and technical details)

Pros

AppSettings(点击上面查看源代码和技术细节)优点

  • 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 Information Services (IIS) Manager中的管理员轻松编辑它们(Features View ->应用程序设置,注意图标的名称具有误导性,因为它只能处理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的配置部分中不直接支持吗