如何使用OpenMappedExeConfiguration()。GetSection()获取旧版IConfigurationSectionHandler

时间:2018-09-12 23:59:09

标签: c# configurationmanager

我有一些使用不推荐使用的IConfigurationSectionHandler的旧代码。如何使用OpenMappedExeConfiguration()。GetSection()获得该部分的配置?

这将返回一个默认部分,但是我无法将类型转换回其原始类型:

var configNew = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var defaultSection = config.GetSection(sectionName);

这是定义自定义配置类型处理程序的方式:

public class ServiceBusConfigurationHandler : IConfigurationSectionHandler
{
    public object Create(object parent, object configContext, System.Xml.XmlNode section)
    {
        using (MemoryStream stm = new MemoryStream())
        {
            using (StreamWriter stw = new StreamWriter(stm))
            {
                stw.Write(section.OuterXml);
                stw.Flush();

                stm.Position = 0;

                XmlSerializer ser = new XmlSerializer(typeof(ServiceBusConfiguration));
                return (ser.Deserialize(stm) as ServiceBusConfiguration);
            }
        }
    }
}

public class ServiceBusConfiguration
{
    private const string MESSAGE_BUS_TYPE = "SB_MessageBusType";
...

不加载单独的配置文件,而是使用以下代码:

    public static ServiceBusConfiguration GetConfig()
    {
        return ConfigurationManager.GetSection("ServiceBusConfiguration") as ServiceBusConfiguration;
    }

我尝试了如下代码,但没有一个可以强制转换该对象:

    public static ServiceBusConfiguration GetConfig(Configuration config1, string clientId)
    {
        var x = (config1.GetSection("ServiceBusConfiguration");
        var y = (NameValueCollection) x;
        return config1.GetSection("ServiceBusConfiguration") as ServiceBusConfiguration;
    }

<section name="ServiceBusSubscribers" type="Project.ServiceBusSubscribersConfiguration,Project.ServiceBus"/>

<ServiceBusSubscribers>
   <group name="Group1" isenabled="false" delete="false">

0 个答案:

没有答案