Adding and reading from a Config file

C#Configuration Files

C# Problem Overview


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 ?

C# Solutions


Solution 1 - C#

  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"].

Solution 2 - C#

Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings;

confCollection["YourKey"].Value = "YourNewKey";


configManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name);

Solution 3 - C#

  1. Right click on the project file -> Add -> New Item -> Application Configuration File. This will add an app.config (or web.config) file to your project.

  2. The ConfigurationManager class would be a good start. You can use it to read different configuration values from the configuration file.

I suggest you start reading the MSDN document about Configuration Files.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIllepView Question on Stackoverflow
Solution 1 - C#goricView Answer on Stackoverflow
Solution 2 - C#Matija GrcicView Answer on Stackoverflow
Solution 3 - C#OdedView Answer on Stackoverflow