using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace ConfigDemo
{
#region CollectionConfigurationSection
public abstract class BaseElementCollection : ConfigurationElementCollection
{
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.AddRemoveClearMap;
}
}
public new string AddElementName
{
get { return base.AddElementName; }
set { base.AddElementName = value; }
}
public new string ClearElementName
{
get { return base.ClearElementName; }
set { base.ClearElementName = value; }
}
public new string RemoveElementName
{
get
{
return base.RemoveElementName;
}
}
public new int Count
{
get { return base.Count; }
}
protected override void BaseAdd(ConfigurationElement element)
{
base.BaseAdd(element);
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(string name)
{
string key = name.ToLower();
BaseRemove(key);
}
public void Clear()
{
BaseClear();
}
}
public class ResearchOrganizationElement : ConfigurationElement
{
public ResearchOrganizationElement()
{
}
public ResearchOrganizationElement(string name)
{
Name = name;
}
[ConfigurationProperty("name", IsRequired = true, IsKey = false)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("companyId", IsRequired = true, IsKey = false)]
public string CompanyId
{
get { return (string)this["companyId"]; }
set { this["companyId"] = value; }
}
}
public class ResearchOrganizationCollection : BaseElementCollection
{
public ResearchOrganizationCollection()
{
}
protected override
ConfigurationElement CreateNewElement()
{
return new ResearchOrganizationElement();
}
protected override
ConfigurationElement CreateNewElement(string elementName)
{
return new ResearchOrganizationElement(elementName);
}
protected override Object
GetElementKey(ConfigurationElement element)
{
return ((ResearchOrganizationElement)element).Name;
}
protected ResearchOrganizationElement this[int index]
{
get { return (ResearchOrganizationElement)BaseGet(index); }
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
public new ResearchOrganizationElement this[string name]
{
get
{
String Key = name.ToLower();
return (ResearchOrganizationElement)BaseGet(name);
}
}
public int IndexOf(ResearchOrganizationElement element)
{
return BaseIndexOf(element);
}
public void Add(ResearchOrganizationElement element)
{
BaseAdd(element);
}
public void Remove(ResearchOrganizationElement element)
{
if (BaseIndexOf(element) >= 0)
{
BaseRemove(element.Name);
}
}
}
public class ReseachOrganizationSection : ConfigurationSection
{
ResearchOrganizationElement element;
public ReseachOrganizationSection()
{
element = new ResearchOrganizationElement();
}
[ConfigurationProperty("researchOrganizations", IsDefaultCollection = false)]
public ResearchOrganizationCollection ResearchOrganizations
{
get
{
ResearchOrganizationCollection collection = (ResearchOrganizationCollection)base["researchOrganizations"];
return collection;
}
}
}
#endregion
#region IConfigurationSectionHandler
public class TableItem
{
public string Name
{
get;
set;
}
public bool IsReload
{
get;
set;
}
}
public class TableSction : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
Dictionary<string, List<TableItem>> sections = new Dictionary<string, List<TableItem>>();
foreach (XmlNode tempNode in section.ChildNodes)
{
if (tempNode.Name == "Type")
{
List<TableItem> tables = new List<TableItem>();
string group = tempNode.Attributes["Name"].Value;
sections.Add(group, tables);
foreach (XmlNode node in tempNode.ChildNodes)
{
if (node.Name == "Table")
{
TableItem item = new TableItem();
item.Name = node.Attributes["Name"].Value.ToLower();
item.IsReload = node.Attributes["IsReload"] == null ? true : bool.Parse(node.Attributes["IsReload"].Value);
tables.Add(item);
}
}
}
}
return sections;
}
}
#endregion
#region ConfigurationSection
public class ServerSection : ConfigurationSection
{
[ConfigurationProperty("User", DefaultValue = "")]
public string User
{
get
{
string name = (string)base["User"];
return name;
}
set
{
base["User"] = "";
}
}
[ConfigurationProperty("PassWord", DefaultValue = "")]
public string PassWord
{
get
{
string pw = (string)base["PassWord"];
return pw;
}
set
{
base["PassWord"] = "";
}
}
}
#endregion
public class ConfigDemocs
{
public static readonly ConfigDemocs Current = new ConfigDemocs();
private ConfigDemocs()
{
InitConfiguration();
}
private Configuration config;
private ReseachOrganizationSection researchOragnizationSection;
public ReseachOrganizationSection ReseachOrganizationSection
{
get
{
return researchOragnizationSection;
}
}
public Dictionary<string, List<TableItem>> TableSction
{
get;
set;
}
public ServerSection ServerSection
{
get;
set;
}
public string mailSender
{
get;
set;
}
public string ConnectionDB
{
get;
set;
}
public void InitConfiguration()
{
ConfigurationSection section;
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = Path.GetFileName(Assembly.GetEntryAssembly().Location + ".config");
config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
TableSction = ConfigurationManager.GetSection("TableSction") as Dictionary<string, List<TableItem>>;
section = config.Sections["ReseachOrganizationSection"];
if (section == null)
{
researchOragnizationSection = new ReseachOrganizationSection();
config.Sections.Add("ReseachOrganizationSection", researchOragnizationSection);
}
else
{
researchOragnizationSection = (ReseachOrganizationSection)section;
}
researchOragnizationSection.SectionInformation.ForceSave = true;
section = config.Sections["ServerSection"];
if (section == null)
{
ServerSection = new ServerSection();
config.Sections.Add("ServerSection", ServerSection);
}
else
{
ServerSection = (ServerSection)section;
}
ServerSection.SectionInformation.ForceSave = true;
mailSender = config.AppSettings.Settings["mailsender"].Value;
ConnectionDB = config.ConnectionStrings.ConnectionStrings["myconn"].ConnectionString;
}
}
}
//调用文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfigDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("******CollectionConfigurationSection******");
ResearchOrganizationElement element = ConfigDemocs.Current.ReseachOrganizationSection.ResearchOrganizations["中信证券"];
Console.WriteLine(element.Name + " " + element.CompanyId + Environment.NewLine);
Console.WriteLine("******IConfigurationSectionHandler******");
Console.WriteLine(ConfigDemocs.Current.TableSction["Basic"][0].Name + " IsReload: " + ConfigDemocs.Current.TableSction["Basic"][0].IsReload + Environment.NewLine);
Console.WriteLine("******ConfigurationSection******");
Console.WriteLine(ConfigDemocs.Current.ServerSection.User + Environment.NewLine);
Console.WriteLine("******AppSetting******");
Console.WriteLine(ConfigDemocs.Current.mailSender + Environment.NewLine);
Console.WriteLine("******ConnectionDB******");
Console.WriteLine(ConfigDemocs.Current.ConnectionDB + Environment.NewLine);
Console.ReadLine();
}
}
}
//配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ReseachOrganizationSection" type="ConfigDemo.ReseachOrganizationSection, ConfigDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<section name="TableSction" type="ConfigDemo.TableSction, ConfigDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<section name="ServerSection" type="ConfigDemo.ServerSection, ConfigDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>
<ReseachOrganizationSection>
<researchOrganizations>
<clear/>
<add name="天风证券" companyId="001"></add>
<add name="中信证券" companyId="002"></add>
</researchOrganizations>
</ReseachOrganizationSection>
<TableSction>
<Type Name="Basic">
<Table Name="User" IsReload="true"/>
<Table Name="Company" IsRload="false"/>
</Type>
<Type Name="Other">
<Table Name="tbOrder" IsReload="true"/>
<Table Name="tbDate" IsRload="false"/>
</Type>
</TableSction>
<ServerSection User="001" PassWord="123"/>
<appSettings>
<add key="mailsender" value="test@qq.com"/>
</appSettings>
<connectionStrings>
<add name="myconn" connectionString="Data Source=.;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=110"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>