Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and reading from a Config file

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 ?
like image 829
Illep Avatar asked Jun 02 '12 18:06

Illep


People also ask

What reads a config file?

Since CONFIG files are stored in plain text, you can view and edit them with a text editor such as Microsoft Notepad.

What do I do with a config file?

The CONFIG File format is used for server processes, software applications, and operating system settings. A programmer can write code to instruct a software to read the configuration files again and again after certain time of period and apply the changes to the current process.


2 Answers

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

like image 119
goric Avatar answered Sep 24 '22 06:09

goric


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); 
like image 37
Matija Grcic Avatar answered Sep 24 '22 06:09

Matija Grcic