1

How to read a personal section in a web.config ?

<MyPersonalSection>
    <add name="toto" enable="true" URL="http://localhost:43242" />
    <add name="titi" enable="false" URL="http://localhost:98762" />
<MyPersonalSection/>

I'd like to get the enable value and/or URL value with the name value.

I also have this mistake : Unrecognized configuration section MyPersonalSection

I been trying

var config = ConfigurationManager.GetSection("MyPersonalSection");

2
  • 1
    What have you tried? Commented Jul 26, 2012 at 12:37
  • <add... is a key/value idiom (e.g. only two attributes), it's confusing to add three attributes to an add element. Commented Jul 26, 2012 at 14:25

3 Answers 3

3

Here is a cool example for that.

Sign up to request clarification or add additional context in comments.

Comments

0

You don't need to write a custom configuration handler to get what you want. There are built-in configuration handlers that you can use if you simply want key-value entries. But, you'll have to use key instead of name and value instead of URL. For example:

<configuration>
 <configSections>
  <section name="MyPersonalSection" type="System.Configuration.NameValueSectionHandler" />
 </configSections>
<MyPersonalSection>
    <add key="toto" value="http://localhost:43242" />
    <add key="titi" value="http://localhost:98762" />
</MyPersonalSection>
</configuration>

And you can access them via code:

var myValues = ConfigurationSettings.GetConfig("MyPersonalSection") as NameValueCollection;
var url = myValues["toto"];

I would suggest naming your keys in a way that makes it clear what the value should be, like "totoUrl" and "titiUrl".

If you want something other than string value pairs, you'll have to write your own custom handler.

3 Comments

Thank you for your help. I already tried that but in my case, it doen't work. I forgot to say that I have 3 values, I edited my first message.
Then you'll need to write you own handler, see laszlokiss88 's answer for a reference.
@Vinhent Writing a custom section handler sometimes requires processing XML text in some way; but, usually you can create classes to represent elements as described in the link that laszlokiss88 provided.
0

You can add appSettings section in your web.config with key that you will need. For example:

<configuration>
   <appSettings>
      <add key="FirstUrl" value="http://localhost:43242"/>
      <add key="SecondUrl" value="http://localhost:98762" />
    </appSettings>
 ...
</configuration>

So, since aspx.cs file, you can declare directive

using System.Configuration;

And later, you can retrieve FirstUrl value in this way:

 var myUrl = ConfigurationManager.AppSettings["FirstUrl"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.