我有一个dll,我想从手动指定的app.config文件中读取(dll是本机com的所有.net扩展,是Microsoft管理控制台的快照,所以没有mmc.exe.config).我已经能够打开配置文件,阅读相关的组和部分以获得我想要的设置.像这样:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = Assembly.GetExecutingAssembly().Location + ".config"; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); ShowSectionGroupCollectionInfo(config.SectionGroups); ConfigurationSectionGroup group = config.SectionGroups["applicationSettings"]; ClientSettingsSection section = group.Sections["Namespace.Properties.Settings"] as ClientSettingsSection; SettingElement sectionElement = section.Settings.Get("AllowedPlugins"); SettingValueElement elementValue = sectionElement.Value;
设置是字符串集合和字符串.像这样:
Plugin1.Name Plugin2.Name Plugin3.Name sajksjaksj
我可以用一点kak手工创建一个字符串数组:
Listvalues = new List (elementValue.ValueXml.InnerText.Split(new string[]{" ",Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries ));
但我想知道是否有一种很好的方式,我错过了我可以将我的设置读取并转换为正确类型的对象,就像读取标准app.config文件时一样.
请告诉我有...
我过去这样做的方式是使用自定义配置部分并IConfigurationSectionHandler
为该部分实现.您仍然必须在配置部分处理程序中执行所有解析,但是这样可以轻松地在您的应用程序中以您希望的形式获取配置部分中的信息.MSDN上的How To文章经历了创建这样一个处理程序的过程.
以下是我用过的一个例子:
用法:
Dictionaryroles = ConfigurationManager.GetSection("roles") as Dictionary ;
web.config中:
...
码:
public class RolesDefinitionHandler : IConfigurationSectionHandler { private static readonly string ROLE_SECTION_NAME = "role"; private static readonly string ROLE_SECTION_NAME_ATTRIBUTE = "name"; private static readonly string ROLE_SECTION_GROUP_ATTRIBUTE = "group"; private DictionaryReadConfiguration( XmlNode section ) { Dictionary roles = new Dictionary (); foreach (XmlNode node in section.ChildNodes) { if (node.Name.Equals( ROLE_SECTION_NAME, StringComparison.InvariantCultureIgnoreCase )) { string name = (node.Attributes[ROLE_SECTION_NAME_ATTRIBUTE] != null) ? node.Attributes[ROLE_SECTION_NAME_ATTRIBUTE].Value.ToLower() : null; if (string.IsNullOrEmpty( name )) { throw new ConfigurationErrorsException( "missing required attribute " + ROLE_SECTION_NAME_ATTRIBUTE ); } string group = (node.Attributes[ROLE_SECTION_GROUP_ATTRIBUTE] != null) ? node.Attributes[ROLE_SECTION_GROUP_ATTRIBUTE].Value.ToLower() : null; if (string.IsNullOrEmpty( group )) { throw new ConfigurationErrorsException( "missing required attribute " + ROLE_SECTION_GROUP_ATTRIBUTE ); } if (roles.ContainsKey( name )) { throw new ConfigurationErrorsException( "duplicate " + ROLE_SECTION_NAME + " for " + name ); } roles.Add( name, new AdministrativeRole( name, group ) ); } else { throw new ConfigurationErrorsException( "illegal node " + node.Name ); } } return roles; } #region IConfigurationSectionHandler Members public object Create( object parent, object configContext, System.Xml.XmlNode section ) { return ReadConfiguration( section ); } #endregion }