简体   繁体   English

是否有可能在.NET(C#)中以编程方式从头创建* .config文件?

[英]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. 对于我们的方法,我们希望从头开始创建一个* .config文件,并在运行时使用一些默认/自定义值填充它。

Is there possibility to do this programatically via ConfigurationManager or something like that? 是否有可能通过ConfigurationManager或类似的方式以编程方式执行此操作?

Yes. 是。 As you point out, the ConfigurationManager class allows you to read and write config files. 正如您所指出的, ConfigurationManager类允许您读取和写入配置文件。

ConfigurationManager Class ConfigurationManager

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. 当然,您可以将这些文件作为XML文件读/写,但上面的类公开了一个更方便的界面来操作配置文件。

To trick the ConfigurationManager into opening an arbitrarily named config file, you can [ab?]use ExeConfigurationFileMap . 要欺骗ConfigurationManager打开任意命名的配置文件,您可以[ab?]使用ExeConfigurationFileMap Note that file may not exist, in which case it will be created when you call Save() 请注意,该file可能不存在,在这种情况下,它将在您调用Save()时创建

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
{
    ExeConfigFilename = file
};
var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
//todo manipulate config. add settings / connection strings etc.
config.Save();

由于.config文件只是XML,因此您应该只需使用XmlTextWriter来构建配置文件。

sure it is, it's a simple and plain xml file 确定它是一个简单而简单的xml文件

now... what config file are you writing about? 现在......你在写什么config文件? app.config ? app.config web.config ? web.config custom.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) 前两个是Windows应用程序和Web应用程序的配置支持 ,因此您需要从“ 外部 ”应用程序生成然后启动该应用程序(已经在安装项目中发生的问题,它要求用户提供的东西,你可以编辑/添加到配置文件,如数据库连接等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM