.net - 如何手动从 app.config 文件中读取强类型对象

标签 .net app-config strong-typing

我有一个 dll,我想从手动指定的 app.config 文件中读取(该 dll 是 native 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>

我可以用一些 kak handed 的方式从中创建一个字符串数组:

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

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

请告诉我有...

最佳答案

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

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

用法:

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

网络配置:

<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
}

关于.net - 如何手动从 app.config 文件中读取强类型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/532517/

相关文章:

python - 如何处理 Python 中不同模块的相关对象之间的循环引用?

c# - 如何在不依赖 WinPCap 的情况下嗅探应用程序中的数据包?

.net - 从数据库查询填充组合框

c# - 如何提高大量较小文件的读写速度或性能

c# - 在开发期间管理多个应用程序配置文件

c# - 如何使用 App.config 连接 C# 和 Db?

c# - 强类型数据集与弱类型数据集

c# - .NET Core 2.0 - 仍然看到没有 'Access-Control-Allow-Origin' header 错误

c# - 如何从另一个程序集读取 app.config?

asynchronous - 用于图像哈希的 Flutter 计算函数