【问题标题】:How to read strongly typed objects from an app.config file manually如何手动从 app.config 文件中读取强类型对象
【发布时间】:2010-10-06 15:50:45
【问题描述】:

我有一个要从手动指定的 app.config 文件中读取的 dll(该 dll 是原生 com dll 的 .net 扩展名,它是 Microsoft 管理控制台管理单元,因此没有 mmc.exe。配置)。我已经能够打开配置文件,阅读相关组和部分以获得我想要的设置。像这样:

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;

设置是一个字符串集合和一个字符串。像这样:

<applicationSettings>
    <Namespace.Properties.Settings>
        <setting name="AllowedPlugins" serializeAs="Xml">
            <value>
                <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                    <string>Plugin1.Name</string>
                    <string>Plugin2.Name</string>
                    <string>Plugin3.Name</string>
                </ArrayOfString>
            </value>
        </setting>
        <setting name="blah" serializeAs="String">
            <value>sajksjaksj</value>
        </setting>
    </Namespace.Properties.Settings>
</applicationSettings>

我可以通过这种方式创建一个字符串数组:

List<String> values = new List<string>(elementValue.ValueXml.InnerText.Split(new string[]{" ",Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries ));

但我想知道是否有一种我错过的好方法可以让我的设置被读取并转换为正确类型的对象,就像读取标准 app.config 文件时一样.

请告诉我有...

【问题讨论】:

    标签: .net app-config strong-typing


    【解决方案1】:

    我过去这样做的方式是使用自定义配置部分并为该部分实现IConfigurationSectionHandler。您仍然必须在配置部分处理程序中进行所有解析,但是它可以轻松地以您希望在应用程序中的形式获取配置部分中的信息。 MSDN 上有一个How To article,它通过了创建此类处理程序的过程。

    下面是我用过的一个例子:

    用法:

    Dictionary<string,AdministrativeRole> roles
            = ConfigurationManager.GetSection("roles")
                 as Dictionary<string,AdministrativeRole>;
    

    web.config:

    <configuration>
       <configSections>
          <section name="roles"
                   type="com.example.RolesDefinitionHandler, com.example" />
       </configSections>
       <roles>
           <role name="Administrator" group="domain\group-name" />
           ...
       </roles>
    </configuration>
    

    代码:

    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 Dictionary<string, AdministrativeRole> ReadConfiguration( XmlNode section )
        {
            Dictionary<string, AdministrativeRole> roles = new Dictionary<string, AdministrativeRole>();
            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
    }
    

    【讨论】:

    • 谢谢。对于默认情况下已经可以解析的类型,这似乎有点过分了。如果我在配置中保留自己的类型,我可以理解这样做,但这是 SpecializedStringCollection 的标准类型。当然我不需要为此做这个?反正我会调查的
    • 您为什么不一路为自定义配置结构中出现的每个 XML 元素创建一个类?
    【解决方案2】:

    一个更好的解决方案可能是,类似于如何将 sql 连接字符串添加到 app.config:

    http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx

    【讨论】:

      猜你喜欢
      • 2011-01-24
      • 2015-12-30
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      相关资源
      最近更新 更多