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 t开发者_运维技巧his programatically via ConfigurationManager or something like that?
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();
Since .config files are just XML, you should be able to just use an XmlTextWriter
to build your config file.
sure it is, it's a simple and plain xml file
now... what config
file are you writing about? app.config
? web.config
? custom.config
?
first two are configuration support for the windows app and web app, so you would need to generate from an "outside" app and then fire that app up (witch that already happens with the Setup project where it asks for the user things and you can edit/add to the configuration file, like Database connections, etc)
精彩评论