Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there possibility to create *.config file from scratch programatically in .NET (C#)?

For our approach we want to create one of the *.config files from scratch and populate it with some default/custom values at runtime.

Is there possibility to do this programatically via ConfigurationManager or something like that?

like image 300
Andriy Buday Avatar asked Dec 12 '22 19:12

Andriy Buday


1 Answers

Yes. As you point out, the ConfigurationManager class allows you to read and write config files.

ConfigurationManager Class

Scroll down a bit.

Sure, you can read / write these files as XML files, but the above class exposes a much handier interface for manipulating config files.

To trick the ConfigurationManager into opening an arbitrarily named config file, you can [ab?]useExeConfigurationFileMap. Note that file may not exist, in which case it will be created when you call Save()

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
{
    ExeConfigFilename = file
};
var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
//todo manipulate config. add settings / connection strings etc.
config.Save();
like image 139
Ziffusion Avatar answered Dec 15 '22 07:12

Ziffusion