-1

I want my app.config file to be something like

<configSections>
    <section name ="RegCompany" type =""/>
</configSections>

<RegCompany>
<Company name="Tata Motors" code="Tata"/>
<SomethingElse url="someuri"/>
</RegCompany>

Any idea how to do this? I want to get the values defined here through my code.

Vasudha Gupta
  • 171
  • 11
  • Incomplete question. Can you please elaborate what are you trying to do. You can just use AppSettings in your current App.config or Web.config for extra config values – HaBo Jan 04 '17 at 10:22
  • I dont want to use appsettings in my code. I want to add a customConfig Section in app.config file so that the developers using my application can easily set these values. – Vasudha Gupta Jan 04 '17 at 10:25
  • what is wrong in the current code which you have put it here? any exception/error you're getting while debugging? – Rahul Hendawe Jan 04 '17 at 10:27
  • @Rahul I cant figure out the actual classes ill have to write to extract these values from app.config. – Vasudha Gupta Jan 04 '17 at 10:29
  • 1
    Googled the words you wrote `"customConfig Section in app.config file"` and the first result links to [How to: Create Custom Configuration Sections Using ConfigurationSection](https://msdn.microsoft.com/en-us/library/2tw134k3.aspx) – Renatas M. Jan 04 '17 at 10:29
  • 1
    Also your custom config section looks identical to this duplicated question (with the answer!!): http://stackoverflow.com/questions/1316058/how-to-create-custom-config-section-in-app-config Please add just a minute of your time to find similar questions. – Renatas M. Jan 04 '17 at 10:33

1 Answers1

2

For simple values like this, there is an easier solution than the one in the duplicate questions.

Config:

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

<RegCompany>
     <add key="CompanyName" value="Tata Motors" />
     <add key="CompanyCode" value="Tata" />
     <add key="CompanyUrl" value="example.com" />
</RegCompany>

Code:

var section = ConfigurationManager.GetSection("RegCompany") as NameValueCollection;
if (section == null) {
    throw new InvalidOperationException("Unknown company");
}

var company = section["CompanyName"];
var code = section["CompanyCode"];
var url = section["CompanyUrl"];
stuartd
  • 70,509
  • 14
  • 132
  • 163