Adding and reading from a Config file

Illep picture Illep · Jun 2, 2012 · Viewed 159.3k times · Source

I have created a C# console based project. In that project i have some variables like companyName, companyType which are Strings.

companyName="someCompanyName";
companyType="someCompanyType";

I need to create a config file and read values from it, and then initialize the variables companyName, companyType in the code.

  1. How can i create a config file (or equivalent) ?
  2. How can i read from the config file ?

Answer

goric picture goric · Jun 2, 2012
  1. Add an Application Configuration File item to your project (Right -Click Project > Add item). This will create a file called app.config in your project.

  2. Edit the file by adding entries like <add key="keyname" value="someValue" /> within the <appSettings> tag.

  3. Add a reference to the System.Configuration dll, and reference the items in the config using code like ConfigurationManager.AppSettings["keyname"].