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

发布于 2024-07-14 04:36:14 字数 2087 浏览 4 评论 0 原文

我有一个 dll,我想从手动指定的 app.config 文件中读取该 dll(该 dll 是本机 com dll 的 .net 扩展名,该 dll 是 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;

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

<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 手动方式从中创建一个字符串数组:

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

但我想知道是否有一种我缺少的好方法可以读取我的设置并将其转换为右侧的对象键入的方式与读取标准 app.config 文件时的方式相同。

请告诉我有...

I have a dll that I want to read from a manually specified app.config file (the dll is an .net extension to a native com dll that is a Microsoft Management Console snap in, so there is no mmc.exe.config). I have been able to open the config file, read the relevant group and section to get the setting that I want. Like this:

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;

The settings are a string collection and a string. like so:

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

I can create a string array from this in a bit of a kak handed way:

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

but I wonder if there is a nice way that I'm missing that I can get my settings to be read and converted into objects of the right type in the same way that they are when the standard app.config file is read.

Please tell me there is...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

转身以后 2024-07-21 04:36:14

我过去完成此操作的方法是使用自定义配置部分并为该部分实现 IConfigurationSectionHandler。 您仍然需要在配置节处理程序中进行所有解析,但是它可以轻松地以您希望在应用程序中使用的形式获取配置节中的信息。 MSDN 上有一篇如何文章,介绍了创建过程这样的处理程序。

下面是我使用过的一个示例:

用法:

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
}

The way that I've done this in the past is use a custom configuration section and implement an IConfigurationSectionHandler for the section. You still have to do all of the parsing inside the configuration section handler, but it makes it easy to get the information in the configuration section in the form you want it in your application. There is a How To article on MSDN that goes through the process of creating such a handler.

Below is an example of one that I've used:

usage:

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>

code:

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
}
随波逐流 2024-07-21 04:36:14

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

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

A better solution might be, which is similar to how sql connection strings are added to a app.config:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文