如何从命令行参数选择 .Net 应用程序配置文件?

发布于 2024-07-07 07:46:18 字数 562 浏览 11 评论 0原文

我想通过传递命令行参数来覆盖标准 app.config 的使用。 如何更改默认应用程序配置文件,以便在访问 ConfigurationManager.AppSettings 时访问命令行上指定的配置文件?

编辑:

事实证明,加载与 EXE 加 .config 名称不同的配置文件的正确方法是使用 OpenMappedExeConfiguration。 例如,

ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Shell2.exe.config");
currentConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);

这部分有效。 我可以看到 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?

Edit:

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);

This partially works. I can see all of the keys in the appSettings section but all the values are null.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

伏妖词 2024-07-14 07:46:18

因此,这里的代码实际上允许我实际访问配置文件中的 appSettings 部分,而不是默认的部分。

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;

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;
近箐 2024-07-14 07:46:18

一个批处理文件,将所需的配置文件复制到 appname.exe.config,然后运行 ​​appname.exe。

A batch file that copies your desired configuration file to appname.exe.config and then runs the appname.exe.

韵柒 2024-07-14 07:46:18

我也需要为我的一个应用程序执行此操作,并且对于这样一个简单的概念,处理标准配置对象变得非常麻烦,所以我采用了这条路线:以

  1. 类似于 app.config 的 XML 格式保留多个配置文件
  2. 将指定的配置文件加载到 DataSet 中(通过 .ReadXML),并使用其中包含配置信息的 DataTable 作为我的配置对象
  3. 因此,我的所有代码都只处理配置数据表来检索值,而不是处理那个极其混乱的应用程序配置对象。

然后我可以在命令行上传入我需要的任何配置文件名,如果不存在 - 只需将 app.config 加载到 DataSet 中。

天啊,在那之后就简单多了。 :-)

罗恩

I needed to do this for an app of mine as well, and dealing with the standard config objects turned into such a freakin' hassle for such a simple concept that I went this route:

  1. Keep multiple config files in XML format similar to app.config
  2. Load the specified config file into a DataSet (via .ReadXML), and use the DataTable with the config info in it as my Configuration object.
  3. So all my code just deals with the Configuration DataTable to retrieve values and not that craptastically obfuscated app config object.

then I can pass in whatever config filename I need on the command line and if one isn't there - just load app.config into the DataSet.

Jeezus it was sooo much simpler after that. :-)

Ron

九公里浅绿 2024-07-14 07:46:18

这不完全是您想要的...重定向实际的 ConfigurationManager 静态对象指向不同的路径。 但我认为这是解决您问题的正确方法。 查看 OpenExeConfiguration 方法ConfigurationManager 类。

如果上述方法不是您想要的,我认为使用 企业库框架的配置功能(由 Microsoft 模式与实践团队开发和维护)。

具体请查看 FileConfigurationSource 类。

下面是一些代码,重点介绍了 企业库,相信这完全符合您的目标。 为此,您需要从 Ent Lib 获取的唯一程序集是 Microsoft.Practices.EnterpriseLibrary.Common.dll。

static void Main(string[] args)
{
    //read from current app.config as default
    AppSettingsSection ass = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings;

    //if args[0] is a valid file path assume it's a config for this example and attempt to load
    if (args.Length > 0 && File.Exists(args[0]))
    {
        //using FileConfigurationSource from Enterprise Library
        FileConfigurationSource fcs = new FileConfigurationSource(args[0]);
        ass = (AppSettingsSection) fcs.GetSection("appSettings");
    }

    //print value from configuration
    Console.WriteLine(ass.Settings["test"].Value);
    Console.ReadLine(); //pause
}

This is not exactly what you are wanting... to redirect the actual ConfigurationManager static object to point at a different path. But I think it is the right solution to your problem. Check out the OpenExeConfiguration method on the ConfigurationManager class.

If the above method is not what you are looking for I think it would also be worth taking a look at using the Configuration capabilities of the Enterprise Library framework (developed and maintained by the Microsoft Patterns & Practices team).

Specifically take a look at the FileConfigurationSource class.

Here is some code that highlights the use of the FileConfigurationSource from Enterprise Library, I believe this fully meets your goals. The only assembly you need from Ent Lib for this is Microsoft.Practices.EnterpriseLibrary.Common.dll.

static void Main(string[] args)
{
    //read from current app.config as default
    AppSettingsSection ass = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings;

    //if args[0] is a valid file path assume it's a config for this example and attempt to load
    if (args.Length > 0 && File.Exists(args[0]))
    {
        //using FileConfigurationSource from Enterprise Library
        FileConfigurationSource fcs = new FileConfigurationSource(args[0]);
        ass = (AppSettingsSection) fcs.GetSection("appSettings");
    }

    //print value from configuration
    Console.WriteLine(ass.Settings["test"].Value);
    Console.ReadLine(); //pause
}
做个少女永远怀春 2024-07-14 07:46:18

这是使用默认配置并通过命令行接受覆盖的应用程序源的相关部分:

将当前或用户配置获取到配置对象中

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string defCfgName = Environment.GetCommandLineArgs()[0] + ".config";

if (arg.Length != 0)
{
    string ConfigFileName = arg[0];
    if (!File.Exists(ConfigFileName))
        Fatal("File doesn't exist: " + ConfigFileName, -1);                
    config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = ConfigFileName }, ConfigurationUserLevel.None);
}
else if (!File.Exists(defCfgName)) Fatal("Default configuration file doesn't exist and no override is set." , -1);

使用配置对象

AppSettingsSection s = (AppSettingsSection)config.GetSection("appSettings");
KeyValueConfigurationCollection a = s.Settings;
ConnectionString = a["ConnectionString"].Value;

This is the relevant part of the source for app that uses default config and accepts override via command line:

Get current or user config into the Config object

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string defCfgName = Environment.GetCommandLineArgs()[0] + ".config";

if (arg.Length != 0)
{
    string ConfigFileName = arg[0];
    if (!File.Exists(ConfigFileName))
        Fatal("File doesn't exist: " + ConfigFileName, -1);                
    config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = ConfigFileName }, ConfigurationUserLevel.None);
}
else if (!File.Exists(defCfgName)) Fatal("Default configuration file doesn't exist and no override is set." , -1);

Use the config object

AppSettingsSection s = (AppSettingsSection)config.GetSection("appSettings");
KeyValueConfigurationCollection a = s.Settings;
ConnectionString = a["ConnectionString"].Value;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文