【问题标题】:How to run a executable program with different configuration file?如何运行具有不同配置文件的可执行程序?
【发布时间】:2014-02-13 15:48:21
【问题描述】:

我想运行一个具有不同配置文件的程序,该程序使用 C# 2.0 编写,我创建了一些不同的文件名 {program_name}.exe.config,我的意思是一个 exe 具有不同的配置文件,例如我有 3 个配置文件,然后我将使用不同的配置文件运行 3 个 exe,但 exe 文件是相同的。 我可以不修改程序以读取不同的配置文件(我不想将配置文件路径放在 exe 命令参数中)来做到这一点(如使用批处理文件或其他方法。)?

谢谢。

【问题讨论】:

  • 你的意思是你有一个可执行文件和三个配置文件,你想选择使用哪一个?

标签: c# .net


【解决方案1】:

您可以更改加载 exe 的应用程序域的配置文件。这是使用 AppDomain 类的 SetData 方法完成的。确保这行代码作为应用程序的第一行执行。

我使用以下代码在 3 个不同的可执行文件之间共享 1 个 exe.config 文件。

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE","yourSharedConfig.exe.config");

你可以看看下面的博文
Binding to custom app.config

如果您想使用 3 个不同的配置运行相同的 exe,我相信相同的方法将适用于一些自定义。您可以在调用 exe 作为命令行参数时传递配置文件的名称,并使用 SetData 方法可以动态设置配置。

【讨论】:

  • 使用AppDomain.CurrentDomain.SetupInformation.ConfigurationFile = "yourSharedConfig.exe.config"不是更好吗?
【解决方案2】:

三个配置和一个可执行文件的主要问题是您需要为可执行文件指定要使用的配置。

一种选择是为您的可执行文件制作 3 个副本,exe1.exeexe2.exeexe3.exe,并为每个具有类似名称的配置 - exe1.exe.configexe2.exe.configexe3.exe.config

当运行每个可执行文件时,它将使用正确的配置。

另一种选择是拥有多个批处理文件,这些批处理文件将根据您要使用的配置文件重命名不同的配置文件。然后你有一个 exe 和三个配置。

【讨论】:

  • 我有类似的情况,我通过将 exe 副本复制到单独的文件夹中来做到这一点。所以我有包含相同可执行文件的文件夹 1、文件夹 2、文件夹 3。然后使用 Windows 批处理文件,我可以使用 START folder1\myexe.exe START folder2\myexe.exe START folder3\myexe.exe 一次启动所有三个
【解决方案3】:

我使用 LINQ 实现并将参数作为 config=path2file 传递

public partial class App : Application {

    private void startup(object sender, StartupEventArgs e) {
        if (null != e) {
            if (null != e.Args && 0 < e.Args.Length) {
                string config = e.Args.Where(a => a.StartsWith("config=")).FirstOrDefault();
                if (null != config) {
                    config = config.Substring("config=".Length);
                    if (File.Exists(config)) {
                        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", config);
                    }
                }
            }
        }
    }

【讨论】:

    【解决方案4】:

    您创建了第二个可执行文件,并且始终首先运行该可执行文件。在其中,您只需将一个配置文件重命名为正确的名称并启动主应用程序。

    string currentConfig = "application.exe.config";
    string someOtherName = "firstconfig.config";
    string configFileYouWant = "secondconfig.config";
    string application = "application.exe";
    
    File.Move(currentConfig, someOtherName);
    File.Move(configFileYouWant, currentConfig);
    Process.Start(application);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      • 2016-01-10
      相关资源
      最近更新 更多