How to use Configuration.GetSection() and ConfigurationManager.OpenMappedExeConfiguration()

Hi all,

I want to access a custom section located in a different config file than the current default one and I managed to use
ConfigurationManager.OpenMappedExeConfiguration() to retrieve a Configuration object for that config file after supplying it with a properly constructed ExeConfigurationFileMap object.

From the Configuration object, I managed to use the
Configuration.GetSection() to retrieve the correct custom section, which uses NameValueSectionHandler.

But after that, I don't know how to obtain the data in the form of NameValueCollection.

Can someone help If it is the default config file, I can simply use the (NameValueSection)ConfigurationManager.GetSection(...).

I managed to use ConfigurationSection.SectionInformation.GetRawXml(), from the return value of GetSection(), to retrieve the xml node of the custom section's data and can see that it contains the correct data.

Thanks.

Rover


Answer this question

How to use Configuration.GetSection() and ConfigurationManager.OpenMappedExeConfiguration()

  • zgchen886

    does anyone know how to do this in Visual Basic
  • marcusp

    I had done exactly what is in the last post and gotten only the "definitions" of the config sections; I cannot get to the name/value pairs in them. Can anybody please help

    Thanks!

    Marilu


  • Hitesh Mangal

    Config File:

    Code Block
    < xml version="1.0" encoding="utf-8" >
    <configuration>
    <connectionStrings>
    <add name="Connection1" connectionString="Data Source=SERVER_NAME1;User ID=USER_ID1;Password=USER_PASSWORD1;Initial Catalog=DATABASE_NAME1;"/>
    <add name="Connection2" connectionString="Data Source=SERVER_NAME2;User ID=USER_ID2;Password=USER_PASSWORD2;Initial Catalog=DATABASE_NAME2;"/>
    </connectionStrings>
    </configuration>



    Application Code:
    Code Block
    Private Sub LoadConnectionStrings(ByVal configFilePath As String)

    Dim fileMap As ExeConfigurationFileMap = New ExeConfigurationFileMap()
    fileMap.ExeConfigFilename = configFilePath

    Try
    Dim config As Configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
    Dim configSection As ConnectionStringsSection = config.ConnectionStrings

    Dim itemIndex As Integer
    For Each connectionSettings As ConnectionStringSettings In configSection.ConnectionStrings
    itemIndex = comboBoxConnectionStrings.Items.Add(connectionSettings.Name)
    Next

    If comboBoxConnectionStrings.Items.Count > 0 Then
    comboBoxConnectionStrings.SelectedIndex = itemIndex
    End If
    Catch ex As ConfigurationErrorsException
    MessageBox.Show(ex.Message, "Configuration Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
    End Sub



    Code Block
    Private Sub SaveConnectionString(ByVal configFilePath As String, ByVal connectionStringName As String, ByVal connectionString As String)
    Dim fileMap As ExeConfigurationFileMap = New ExeConfigurationFileMap()
    fileMap.ExeConfigFilename = configFilePath

    Try
    Dim config As Configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
    Dim configSection As ConnectionStringsSection = config.ConnectionStrings

    If configSection IsNot Nothing Then
    If configSection.IsReadOnly() = False And configSection.SectionInformation.IsLocked = False Then
    configSection.ConnectionStrings(connectionStringName).ConnectionString = connectionString
    config.Save()
    End If
    End If
    Catch ex As ConfigurationErrorsException
    MessageBox.Show(ex.Message, "Configuration Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
    End Sub




  • Jay Williams

    Has anyone managed to solve the original problem Rover wanted to be able to get at an old .Net 1.1-style config section from a configuration file he knows by name (not his app's default config file).

    The various replies of "working" code are nice, but none of them solves his problem.

    nrolland and manit's code samples work because ClientSettingsSection and AppSettingsSection are net 2.0-style classes derived from ConfigurationSection. This doesn't work for old section types, like Rover's NameValueSectionHandler.

    TommieLand's code works because he's reading out of the default config file. For some wacky reason, ConfigurationManager.GetSection returns a well-formed section, but if you have a Configuration object in your hands, you can't get the same section from its properties.

    I have a more detailed lament at this newer post.

  • TheQuasar

    Nicolas,

    Would you please also provide the .config file contents that this code is working against

    It would greatly help us understand what it is doing.

    Thanks,

    Robert



  • JulienH

    Thanks Stephen,

    I still have trouble following your suggestion. I am using beta 2 and the documentation is not exactly detail.
    This is my test config file:
    < xml version="1.0" encoding="utf-8" >
    <configuration>
    <configSections>
        <section name="MyDemo1"
                 type="System.Configuration.SingleTagSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections>

    <MyDemo1 person1="Peter" person2="Mary" person3="John" />
    </configuration>

    I did this:
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration
         (fileMap, ConfigurationUserLevel.None);
    Debug.Assert(config != null, "Must have a config object");
    ConfigurationSection section = config.GetSection("MyDemo1");

    The config object is of type DefaultSection, which derives from ConfigurationElement which has a protected property called ConfigurationPropertyCollection. From which I could use the indexer, but I can't.

    Because this is a protected properties that DefaultSection does not exposed. It only exposes this type called ElementInformation which to me appears to be of little value.

    I could see the XML data in the section via
    section.SectionInformation.GetRawXml()

    So far, I make use of this to construct a collection from SingleTagSectionHandler.Create() or NameValueSectionHandler.Create(), depending on the section handler I use.

    Does this seem to be the long and wrong way Perhaps you can provide further guidance.

    Thanks.


  • Patricius

    I succeded in accessing the applicationSettings section of a foreign configuration file with OpenMappedExeConfiguration using the following

         ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
    
         fileMap.ExeConfigFilename = Environment.CurrentDirectory + @"\plugins\ProjectionServer\SG.Service.Projection.dll.config";
         if (! File.Exists(fileMap.ExeConfigFilename)) 
         {
           send("Configuration file required :" + fileMap.ExeConfigFilename, LogLevel.Error);
           return;
         }
         Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
         ClientSettingsSection section = (ClientSettingsSection) config.GetSection("applicationSettings/SG.Server.Properties.Settings");
    
         string servername = section.Settings.Get("server").Value.ValueXml.InnerText;
         string port = section.Settings.Get("port").Value.ValueXml.InnerText;
         string file = section.Settings.Get("projectionfilelocation").Value.ValueXml.InnerText;
    

    It would be good if a definite guide was written on it, because there are many aspects in the new settings architecture beside just using it. From what I have seen it is a whole runtime typing system for settings that is in place now.

    Nicolas Rolland


  • tassie

    Hello Rover,

    I don't know of a way to retrieve a NameValueCollection from the the ConfigurationSection class.

    However, the class that derived from ConfigurationSection should have surfaced the name values, via the ConfigurationProperty [indexer] on the ConfigurationElement base class.

    You can probably find more community support for this question in the ASP.NET Developer Forums at: http://forums.asp.net

    Hope that helps,
    Stephen
    http://blogs.msdn.com/stfisher

  • Amr Mahmoud

    and here it is....

    I think that it's due to the fact that an app.config file becomes an app.exe.config file when it is compiled.

    So, you need to use:

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

    fileMap.ExeConfigFilename = GetFilename();

    Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

    then when you access configuration to get sections using:

    ConfigurationSection configSection = configuration.GetSection("Categories");

    You actually get a value, since the filename is mapped to the target filename.

    Seems to make sense, just not obvious what a mapped filename is until you stumble across it!

    Good luck,

    Martin.



  • FBYJ

    //*************************************************

    //* Sample program

    //*************************************************

    //********** For App.config

    <configuration>

    <configSections>

    <sectionGroup name="groupInfo">

    <section name="sectionInfo1" type="System.Configuration.NameValueSectionHandler"/>

    <section name="sectionInfo2" type="System.Configuration.NameValueSectionHandler"/>

    </sectionGroup>

    </configSections>

    <groupInfo>

    <sectionInfo1>

    <add key="myKeyA" value="AAA"/>

    <add key="myKeyB" value="BBB"/>

    </sectionInfo1>

    </groupInfo>

    </configuration>

    //********** For program

    NameValueCollection nvc =

    (NameValueCollection)ConfigurationManager.GetSection("groupInfo/sectionInfo1");

    for (int i = 0; i < nvc.Count; i++)

    {

    Console.WriteLine( nvc[ i ] + " = " + nvc.Keys[ i ] );

    }



  • Scripto

    Hello,

    I encounter the same problem.. Could you tell us how did you handle this

    N


  • CoNNect

    This is the code i tested with:

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

    fileMap.ExeConfigFilename = @"C:\Inetpub\Test\Config\Dev.config";

    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

    AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");

    string ConfigVersion = section.Settings["ConfigVersion"].Value;

    Response.Write(ConfigVersion);

    - Config file was taken from a web.config

    < xml version="1.0" >
    <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <
    appSettings><add key="ConfigVersion" value="DEV"/>
    </appSettings>
    <
    connectionStrings>
    </connectionStrings>
    </
    configuration>



  • dotNOT4me

    I have also had the same problem.

    All the posts I see say how to access the non-default config file, which just doesn't work for me at all.

    One thing I noticed though, which leads me to think that there might be a bug...

    I loaded the file using the full path, and have to include the .config extension for the file to load without throwing an exception. So I use c:\\mySettings.config as the filename.

    Then, when I subsequently access the configuration object, to use .GetSection("MySection") the filename for the configuration is now what it was before with .config on the end, so in the example above, it now shows c:\\mySettings.config.config!

    I'm going to suppose that that's what is messing things up, however, I can't find any way yet to test the theory, since the file cannot be opened without assuming the .config extension, it's difficult.

    I've looked through all the available sections, and there's 20 of them, which I'm also confused about, they're things like system, windows, connection strings, satelliteassemblies and such like, which I certainly didn't put there, but nowhere in either the Sections or the SectionGroups is there my section, or if it is, I at least can't find it.

    I originally wrote the config file using my custom ConfigurationElement, ConfigurationElementCollection, and configurationSection classes, and the ConfigurationManager.Save(), which appearas to work quite nicely, so I'm fairly sure that I didn't cause any problems with declarations or syntax in the config file.

    I will continue to look into this, but so far, I've come up blank, there's nothing I can see that I'm doing differently to what the various examples say, and yet it doesn't work, however the examples are either very simple, or incomplete snippets in the main.

    The examples in this thread so far appear to be using application settings, or default configurations, neither of which is difficult or problematic.

    I'm sorry I don't have better news, and I hope someone else comes on here with a solution to the problems,

    Martin.



  • decrypted

    Additionally, I just noticed....

    filePath property displays with the extra .config added to the end of the filename, and HasFile property is false, indicating that this configuration does not have a file, and so is new.

    Seriously looks like I need a property to stop the addition of the .config then the file will be there, and all will be good...

    Martin.



  • How to use Configuration.GetSection() and ConfigurationManager.OpenMappedExeConfiguration()