C# – How to run a executable program with different configuration file

cnet

I want to run a program with different configuration file, the program write with C# 2.0, I make some different file name {program_name}.exe.config, I mean one exe with different config file, for example I have 3 config file, then I will run 3 exe with the different config file, bu the exe file is the same one.
Can I do not modify the program for read the different config file (I don`t want to put the config file path in the exe command parameters) to do that(like use the batch file or other method.) ?

Thanks.

Best Answer

You can change the configuration file for the application domain in which the exe is loaded. This is done using the SetData method of the AppDomain class. Ensure that this line of code is executed as the first line of your application.

I have used following code to share 1 exe.config file between 3 different executables.

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

You can look at the following blog entry
Binding to custom app.config

If you want to run the same exe with 3 different configs, I believe the same approach will work with bit of customization. You can pass the name of the config file while invoking the exe as a command line parameter and using the SetData method you can dynamically set the config.