将其封装成类,供以后使用。
命名空间:
using System.Collections.Generic; using System.Configuration; using System.Linq;
类:
public class Config { public Configuration configObject; /// <summary> /// 根据路径获取配置文件 /// </summary> /// <param name="key">键值</param> /// <returns></returns> public Config(string configPath) { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = configPath; this.configObject = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); } public string GetConfig(string key) { string val = string.Empty; if (this.configObject.AppSettings.Settings.AllKeys.Contains(key)) val = this.configObject.AppSettings.Settings[key].Value; return val; } /// <summary> /// 获取所有配置文件 /// </summary> /// <returns></returns> public Dictionary<string, string> GetConfig() { Dictionary<string, string> dict = new Dictionary<string, string>(); foreach (string key in this.configObject.AppSettings.Settings.AllKeys) dict.Add(key, this.configObject.AppSettings.Settings[key].Value); return dict; } /// <summary> /// 根据键值获取配置文件 /// </summary> /// <param name="key">键值</param> /// <param name="defaultValue">默认值</param> /// <returns></returns> public string GetConfig(string key, string defaultValue) { string val = defaultValue; if (this.configObject.AppSettings.Settings.AllKeys.Contains(key)) val = this.configObject.AppSettings.Settings[key].Value; if (val == null) val = defaultValue; return val; } /// <summary> /// 写配置文件,如果节点不存在则自动创建 /// </summary> /// <param name="key">键值</param> /// <param name="value">值</param> /// <returns></returns> public bool SetConfig(string key, string value) { try { //Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (!this.configObject.AppSettings.Settings.AllKeys.Contains(key)) this.configObject.AppSettings.Settings.Add(key, value); else this.configObject.AppSettings.Settings[key].Value = value; this.configObject.Save(ConfigurationSaveMode.Modified); //ConfigurationManager.RefreshSection("appSettings"); return true; } catch { return false; } } /// <summary> /// 写配置文件(用键值创建),如果节点不存在则自动创建 /// </summary> /// <param name="dict">键值集合</param> /// <returns></returns> public bool SetConfig(Dictionary<string, string> dict) { try { if (dict == null || dict.Count == 0) return false; //Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); foreach (string key in dict.Keys) { if (!this.configObject.AppSettings.Settings.AllKeys.Contains(key)) this.configObject.AppSettings.Settings.Add(key, dict[key]); else this.configObject.AppSettings.Settings[key].Value = dict[key]; } this.configObject.Save(ConfigurationSaveMode.Modified); return true; } catch { return false; } } } public class ItemsSection : ConfigurationSection { [ConfigurationProperty("items", IsRequired = true)] public string Category { get { return (string)base["Category"]; } set { base["Category"] = value; } } [ConfigurationProperty("", IsDefaultCollection = true)] public ItemElementCollection Books { get { return (ItemElementCollection)base[""]; } } } public class ItemElementCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new ItemElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((ItemElement)element).Name; } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } protected override string ElementName { get { return "item"; } } public ItemElement this[int index] { get { return (ItemElement)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } } public class ItemElement : ConfigurationElement { [ConfigurationProperty("name", IsRequired = true)] public string Name { get { return (string)base["name"]; } set { base["name"] = value; } } [ConfigurationProperty("icon", IsRequired = true)] public string Icon { get { return (string)base["icon"]; } set { base["icon"] = value; } } [ConfigurationProperty("assembly", IsRequired = true)] public string Assembly { get { return (string)base["assembly"]; } set { base["assembly"] = value; } } [ConfigurationProperty("target", IsRequired = true)] public string Target { get { return (string)base["target"]; } set { base["target"] = value; } } [ConfigurationProperty("kind", IsRequired = true)] public string Kind { get { return (string)base["kind"]; } set { base["name"] = value; } } }
自己的.config文件:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="items" type="Helper.ItemsSection, Helper" /> </configSections> <appSettings> <add key="Header" value="AstroATE通用测试平台"/> <add key="StartTest" value="测试程序" /> <add key="SelfTest" value="自检表格" /> <add key="StartTestName" value="功能测试程序" /> <add key="SelfTestName" value="自检列表.vi" /> <add key="ProName1" value="ATE" /> <add key="sqlitename" value="astroate.db" /> </appSettings> <items> <item name="用户管理" icon ="images\playstore.png" assembly ="MyControlLibrarys" target="UserInterface" kind="0"/> <!--<item name="项目信息" icon ="images\settings-flat.png" assembly ="MyControlLibrarys" target="UserManage"/>--> <!--<item name="资源配置" icon ="images\arrow-download-icon.png" assembly ="MyControlLibrarys" target="UserManage"/>--> <!--<item name="系统设置" icon ="images\settings-flat.png" assembly ="MyControlLibrarys" target="UserManage"/>--> <item name="系统自检" icon ="images\settings-flat.png" assembly ="MyControlLibrarys" target="SelfTest" kind="1"/> <item name="项目执行" icon ="images\play-icon.png" assembly ="MyControlLibrarys" target="StartTest" kind="1"/> <item name="数据管理" icon ="images\arrow-download-icon.png" assembly ="MyControlLibrarys" target="SwitchInterface" kind="0"/> <item name="操作日志" icon ="images\Pencil.ico" assembly ="MyControlLibrarys" target="LoggerInterface" kind="0"/> <item name="帮助文档" icon ="images\Pencil.ico" assembly ="MyControlLibrarys" target="HelpPDF" kind="0"/> </items> </configuration>
其中MyControlLibrarys为我自己生成的库,有以target的值命名的用户控件。
调用:
public Helper.Config configHelper; //配置文件对象
//从配置文件中读取抬头 Helper.Config config = new Config(System.Environment.CurrentDirectory + "/AstroATE.Config"); this.Title = config.GetConfig("Header"); configHelper = new Config(System.Environment.CurrentDirectory + "/AstroATE.Config"); //AstroATE.Config为我的配置文件名 ItemsSection mySectioin1 = (ItemsSection)configHelper.configObject.GetSection("items"); for (int i = 0; i < mySectioin1.Books.Count; i++) { HamburgerMenuGlyphItem hm = new HamburgerMenuGlyphItem(); hm.Glyph = mySectioin1.Books[i].Icon; hm.Label = mySectioin1.Books[i].Name; hm.Tag = mySectioin1.Books[i]; //HamburgerMenuItemCollection hmc = HamburgerMenuControl.ItemsSource as HamburgerMenuItemCollection; // hmc.Add(hm); ItemsInfo tempstruct = new ItemsInfo(); tempstruct.name = mySectioin1.Books[i].Name; tempstruct.kind = mySectioin1.Books[i].Kind; tempstruct.icon = mySectioin1.Books[i].Icon; Helper.ItemElement item = hm.Tag as Helper.ItemElement; string filepath = System.Environment.CurrentDirectory + "\\" + item.Assembly + ".dll"; Assembly assem = Assembly.LoadFrom(filepath); ContentControl oh = (ContentControl)assem.CreateInstance(item.Assembly + "." + item.Target); tempstruct.target = oh; leftitems.Add(tempstruct); }