configSections 自定义 配置节 分离 学习 实例 源码

configSections 自定义 配置节 学习  实例

.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //LcsCopyright 配置节

        LCS.Configration.Copyright data;
        //data = System.Configuration.ConfigurationSettings.GetConfig("LcsCopyright") as LCS.Configration.Copyright;//已过时
        data = System.Configuration.ConfigurationManager.GetSection("LcsCopyright") as LCS.Configration.Copyright;//得到配置节的数据

        Response.Write(data.AppName);
        Response.Write(data.AppVer);
        // 输出
        // Lcs Configration Test 1.0 bate


        Response.Write("<hr/>");
        //LcsAppConfig 配置节

        //载入配置节    这句话可以放在 Global.asax 的 Application_Start 中实现
        System.Configuration.ConfigurationSettings.GetConfig("LcsAppConfig");
        Response.Write(LCS.Configration.AppConfig.ConnectionString);
        Response.Write(LCS.Configration.AppConfig.UserCount);
        //输出
        // this is a ConnectionString199
    }
}

web.config

<?xml version="1.0" encoding="utf-8"?>

<configuration>
   
    <configSections>
        <section name="LcsCopyright" type="LCS.Configration.Settings" /><!--若有生成的dll名称,则后面还要加上,dll程序集名称-->
        <section name="LcsAppConfig" type="LCS.Configration.AppConfig" /><!--这里实验直接放在App_Code里面了,所有不用写程序集名称-->
    </configSections>
   
    <LcsCopyright>
        <AppName> Lcs Configration Test</AppName>
        <AppVer> 1.0 bate</AppVer>
        <AppAuthor> Lcskey</AppAuthor>
    </LcsCopyright>
    <LcsAppConfig>
        <add key="ConnectionString" value="this is a ConnectionString" />
        <add key="UserCount" value="199" />
    </LcsAppConfig>
   
</configuration>


.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;

namespace LCS.Configration
{
    public class Settings : System.Configuration.IConfigurationSectionHandler
    {
        /// <summary>
        /// 实现该接口的Create方法
        /// ConfigurationSettings.GetConfig("")方法会自动调用此方法 给相应的实体属性赋值
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="input"></param>
        /// <param name="node"></param>
        /// <returns></returns>
        public object Create(object parent, object input, XmlNode node)
        {
            Copyright data = new Copyright();
            foreach (XmlNode xn in node.ChildNodes)
            {
                switch (xn.Name.ToLower())
                {
                    case ("appname"):
                        data.AppName = xn.InnerText;
                        break;
                    case ("appver"):
                        data.AppVer = xn.InnerText;
                        break;
                    case ("appauthor"):
                        data.AppAuthor = xn.InnerText;
                        break;
                }
            }
            return data;
        }
    }

    /// <summary>
    /// 从配置节中读取的版权配置节信息对应实体
    /// </summary>
    public class Copyright
    {
        public string AppName;
        public string AppVer;
        public string AppAuthor;
    }






    /// <summary>
    /// 我们把所有的配置都映射成相应的静态成员变量
    /// 并且是写成只读属性
    /// 这样程序通过类似
    /// AppConfig.ConnectionString
    /// 就可以访问配置文件中的项目了
    /// 读取之前需要调用
    /// System.Configuration.ConfigurationSettings.GetConfig("LcsAppConfig");
    /// 调用自己实现了IConfigurationSectionHandler接口的AppConfig来读取配置
    /// </summary>
    public class AppConfig : System.Configuration.IConfigurationSectionHandler
    {
        static String m_connectionString = String.Empty;
        static Int32 m_userCount = 0;
        public static String ConnectionString
        {
            get
            {
                return m_connectionString;
            }
        }
        public static Int32 UserCount
        {
            get
            {
                return m_userCount;
            }
        }

        static String ReadSetting(System.Collections.Specialized.NameValueCollection nvc, String key, String defaultValue)
        {
            String theValue = nvc[key];
            if (theValue == String.Empty)
                return defaultValue;

            return theValue;
        }

        public object Create(object parent, object configContext, XmlNode section)
        {
            System.Collections.Specialized.NameValueCollection settings;

            try
            {
                System.Configuration.NameValueSectionHandler baseHandler = new System.Configuration.NameValueSectionHandler();
                settings = (System.Collections.Specialized.NameValueCollection)baseHandler.Create(parent, configContext, section);
            }
            catch
            {
                settings = null;
            }

            if (settings != null)
            {
                m_connectionString = AppConfig.ReadSetting(settings, "ConnectionString", String.Empty);
                m_userCount = Convert.ToInt32(AppConfig.ReadSetting(settings, "UserCount", "0"));
            }

            return settings;
        }
    }
}


分离配置节
web.config
<?xml version="1.0" encoding="utf-8"?>

<configuration>
   
    <configSections>
        <section name="LcsCopyright" type="LCS.Configration.Settings"/><!--若有生成的dll名称,则后面还要加上,dll程序集名称-->
        <section name="LcsAppConfig" type="LCS.Configration.AppConfig" restartOnExternalChanges="true" /><!--这里实验直接放在App_Code里面了,所有不用写程序集名称-->
    </configSections>
   
   
    <!--<LcsCopyright>
        <AppName> Lcs Configration Test</AppName>
        <AppVer> 1.0 bate</AppVer>
        <AppAuthor> Lcskey</AppAuthor>
    </LcsCopyright>-->

    <!--<LcsAppConfig>
        <add key="ConnectionString" value="this is a ConnectionString" />
        <add key="UserCount" value="199" />
    </LcsAppConfig>-->
   
   
   
    <appSettings configSource="app.config" />
    <connectionStrings configSource="conn.config" />
   

    <!--将自定义的配置节分离出去-->
    <LcsCopyright configSource="LcsCopyright.config" />
    <LcsAppConfig configSource="LcsAppConfig.config"/>
   
</configuration>


app.config
<appSettings>
<add key="a" value="changed by application runtime" />
</appSettings>

conn.config
<connectionStrings>
    <add name="c" connectionString="dbconnention....123" />
</connectionStrings>

LcsCopyright.config
<?xml version="1.0" encoding="utf-8"?>

<LcsCopyright>
    <AppName> Lcs Configration Test</AppName>
    <AppVer> 1.0 bate</AppVer>
    <AppAuthor> Lcskey</AppAuthor>
</LcsCopyright>

LcsAppConfig.config
<?xml version="1.0" encoding="utf-8"?>
<LcsAppConfig>
    <add key="ConnectionString" value="this is a ConnectionString" />
    <add key="UserCount" value="199" />
</LcsAppConfig>

修改web.config.添加上述文件,在同一个目录下面
再运行程序看看,效果一样,数据全部都能读取到。
.aspx 还是原来的,没动代码
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        //LcsCopyright 配置节

        LCS.Configration.Copyright data = new LCS.Configration.Copyright();
        //data = System.Configuration.ConfigurationSettings.GetConfig("LcsCopyright") as LCS.Configration.Copyright;//已过时
        data = System.Configuration.ConfigurationManager.GetSection("LcsCopyright") as LCS.Configration.Copyright;//得到配置节的数据

        Response.Write(data.AppName);
        Response.Write(data.AppVer);
        // 输出
        // Lcs Configration Test 1.0 bate


        Response.Write("<hr/>");
        //LcsAppConfig 配置节

        //载入配置节    这句话可以放在 Global.asax 的 Application_Start 中实现
        System.Configuration.ConfigurationSettings.GetConfig("LcsAppConfig");
        Response.Write(LCS.Configration.AppConfig.ConnectionString);
        Response.Write(LCS.Configration.AppConfig.UserCount);
        //输出
        // this is a ConnectionString199



        //分解web.config
        Response.Write("<hr/>");


        //appSettings 配置节
        Response.Write(System.Configuration.ConfigurationManager.AppSettings["a"]);
        Response.Write("<br/>");
        //connectionStrings 配置节
        Response.Write(System.Configuration.ConfigurationManager.ConnectionStrings["c"]);


        //修改appSettings配置节而不会重起应用程序
        //若需要重起,可设置配置节的 restartOnExternalChanges 属性
        System.Configuration.Configuration cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        System.Configuration.AppSettingsSection appSetting = cfg.AppSettings;
        appSetting.Settings["a"].Value = "changed by application runtime";
        cfg.Save();

    }

}

 

 参考了部分园子里的文章和MSDN。现学现卖。

以前只把app和conn分离出来过,自定义的只是想着应该可以分离,但从来都没有试过。今天小试了一下,还不错。

能直接跑起来的实例源码

posted on 2008-10-24 23:32  lcs-帅  阅读(1536)  评论(0编辑  收藏  举报

导航