我该如何选择一个命令行参数.Net应用程序的配置文件? [英] How do I select a .Net application configuration file from a command line parameter?
问题描述
我想传递一个命令行参数来覆盖使用标准的app.config的。如何更改默认的应用程序配置文件,这样,当我访问ConfigurationManager.AppSettings我访问命令行上指定的配置文件?
I would like to override the use of the standard app.config by passing a command line parameter. How do I change the default application configuration file so that when I access ConfigurationManager.AppSettings I am accessing the config file specified on the command line?
编辑:
事实证明,正确的方式来加载配置文件比EXE文件加的.config是使用OpenMappedExeConfiguration的名称不同。例如。
It turns out that the correct way to load a config file that is different than the name of the EXE plus .config is to use OpenMappedExeConfiguration. E.g.
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Shell2.exe.config");
currentConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);
这部分工作。我可以看到所有的的appSettings的关键部分,但所有的值都为空。
This partially works. I can see all of the keys in the appSettings section but all the values are null.
推荐答案
因此,这里是code,实际上可以让我真正访问appSettings部分比默认的。
So here is the code that actually allows me to actually access the appSettings section in a config file other than the default one.
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Alternate.config");
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);
AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");
string MySetting = section.Settings["MySetting"].Value;
这篇关于我该如何选择一个命令行参数.Net应用程序的配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!