自定义部分是一个很棒的工具!不要将 appSettings 用于严肃的应用程序。
这是自定义部分的代码
在 WEB.CONFIG 中
<configuration>
<configSections>
<section name="Misc" type="Config"/> <<-- this registers a custom section called Misc
<Misc configSource="config_misc.config"/> <<-- this says to look for for it in file "config_misc.config"
(...)
然后在你网站的根目录下创建一个文件CONFIG_MISC.CONFIG并放进去
<Misc
MySetting1="true"
/>
然后在你的 webapp 中,在 APP_CODE 文件夹中,创建一个像这样的类:
using System;
using System.Collections;
using System.Configuration;
using System.Xml;
using System.Collections.Specialized;
public class Config : ConfigurationSection
{
private static string _CONFIG_SECTION = "Misc";
#region singleton implementation
private static Config _config;
static Config()
{
_config = (Config)ConfigurationSettings.GetConfig(_CONFIG_SECTION);
}
#endregion
public static bool MySetting1
{
get
{
return _config._MySetting1;
}
}
#region public properties the define the config items we are looking for
[ConfigurationProperty("MySetting1", IsRequired = false)]
public bool _MySetting1
{
get
{
return (bool)this["MySetting1"];
}
}
#endregion
}
此代码是我的代码的副本,因此在剪切时,我可能犯了一个错误,但它应该可以帮助您入门。
您现在可以通过 Config.MySetting1 以一种非常简单的方式访问您的设置
将您的设置分解为更多 .config 文件也有很多好处,尤其是在维护和模块化方面