user277498 user277498 - 19 days ago 6
C# Question

reading content of an config file into the dll associated with it

I have saved strings in a dll application's setting. I want to retireve them.

Here is the configuration file for my dll:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxxxxxxx" >
<section name="Search.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxx" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<PishiSearch.Properties.Settings>
<setting name="ReadIndex" serializeAs="String">
<value>C:\Index</value>
</setting>
<setting name="WriteIndex" serializeAs="String">
<value>C:\WriteIndex</value>
</setting>
</PishiSearch.Properties.Settings>
</applicationSettings>
</configuration>


It resides in the same directory as my dll. It is called: Search.dll.config
My dll is called: Search.dll

I want to read the values of ReadIndex and WriteIndex from this config file into my dll.

Here is the code:

var executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var location = executingAssembly.Location; //C:\MyApp\bin\Debug\Search.dll
var config = ConfigurationManager.OpenExeConfiguration(location);
var sections = config.Sections; //count of this is 21
ConfigurationSectionGroup csg = config.GetSectionGroup("applicationSettings");
ConfigurationSectionCollection csc = csg.Sections;
ConfigurationSection cs = csc.Get("Search.Properties.Settings");


The code works up to getting the last line here. But how do I get the settings strings?

Yes I can use
cs.SectionInformation.GetRawXml();
to get the xml and then interrogate it to get the values, but that is a kluge.

How do I read the values? Preferably into a Settings object? Many thanks!

Answer
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <applicationSettings>

    </applicationSettings>
    <appSettings>
        <add key="ReadIndex" value="C:\Index"/>
    </appSettings>
</configuration>


var executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var location = executingAssembly.Location; //C:\MyApp\bin\Debug\Search.dll
var config = ConfigurationManager.OpenExeConfiguration(location);
var sections = config.Sections; //count of this is 21
string s = config.AppSettings.Settings["ReadIndex"].Value.ToString();
Comments