網站中有很多需要設置的內容,像網站信息,注冊設置,上傳設置等。如果保存在數據庫中需要單獨建張表,表中只有一條記錄,這樣會讓數據庫很臃腫,而且頻繁存取數據庫的效率也是個問題。而保存在config文件里是個不錯選擇,而且帶有緩存功能!
我們可以在web.config的配置節寫入配置。
<configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <!--這里可以定義配置節 --> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> </configSections>
但是把大量的配置都寫入這里也會造成web.config的臃腫,可以采用把配置節定義在這里,把具體配置信息保存在其他文件中。
以上傳配置信息為例,看一下理想的結構

Config/Upload.config的內容

1、配置的元素。采用<add />的形式,是一個鍵和值得表示形式。<add key="MaxSize" value="1500000" />。
2、元素的集合,里面定義一系列的元素。<UploadConfig>……</UploadConfig>
3、自定義節,表示自定義的一個節點。<section name="UploadConfig" type="Ninesky.Models.Config.UploadConfig, Ninesky.Models"/>
name:節點名,type:處理節點的類行,逗號前是類名,逗號后是縮在程序集。
我們要創建這個類來管理配置
一、創建鍵,值元素類。
里面只有兩個讀寫屬性key和value,內容非常簡單
using System.Configuration;namespace Ninesky.Models.Config{ /// <summary> /// 鍵值元素類 /// <remarks> /// 創建:2014.03.09 /// </remarks> /// </summary> public class KeyValueElement:ConfigurationElement { /// <summary> /// 鍵 /// </summary> [ConfigurationProperty("key",IsRequired=true)] public string Key { get { return this["key"].ToString(); } set { this["key"] = value; } } /// <summary> /// 值 /// </summary> [ConfigurationProperty("value")] public string Value { get { return this["value"].ToString(); } set { this["value"] = value; } } }}二、創建元素集合類。內容很簡單都進行了注釋
using System;using System.Configuration;namespace Ninesky.Models.Config{ /// <summary> /// 元素集合類 /// <remarks> /// 創建:2014.03.09 /// </remarks> /// </summary> [ConfigurationCollection(typeof(KeyValueElement))] public class KeyValueElementCollection:ConfigurationElementCollection { //忽略大小寫 public KeyValueElementCollection() : base(StringComparer.OrdinalIgnoreCase) { } /// <summary> /// 集合中指定鍵的元素 /// </summary> /// <param name="name"></param> /// <returns></returns> new public KeyValueElement this[string name] { get { return (KeyValueElement)base.BaseGet(name); } set { if (base.Properties.Contains(name)) base[name] = value; else base.BaseAdd(value); } } /// <summary> /// 創建新元素. /// 必須重寫 /// </summary> /// <returns></returns> protected override ConfigurationElement CreateNewElement() { return new KeyValueElement(); } /// <summary> /// 獲取元素的鍵 /// </summary> /// <param name="element"></param> /// <returns></returns> protected override object GetElementKey(ConfigurationElement element) { return ((KeyValueElement)element).Key; } }}
新聞熱點
疑難解答
圖片精選