C# Run Another Program and Specify App.Config File

1.7k views Asked by At

I have a test program in which I'm calling another program (let's call this the main program) with System.Diagnostics. I'm having issues specifying which App.Config the test program is using. It seems to always default to using the main program's app.config. Is there a way to specify which file to use without changing the main program to use program arguments? See my code below.

  Process process = new Process();
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.FileName = @"...\MainProgram.exe";
  process.StartInfo.CreateNoWindow = false;
  process.StartInfo.WorkingDirectory = @"...\TestProgram\bin\Debug";
  process.Start();
3

There are 3 answers

2
NicoRiff On BEST ANSWER

I assume you can copy the file you want to use to ensure that it is the one you need.

Use File.Copy to accomplish that.

  File.Copy(@"C:\yourCorrectFilePath\App.Config", @"...\TestProgram\bin\Debug\App.Config", true);
  Process process = new Process();
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.FileName = @"...\MainProgram.exe";
  process.StartInfo.CreateNoWindow = false;
  process.StartInfo.WorkingDirectory = @"...\TestProgram\bin\Debug";
  process.Start();
0
Dan Trausch On

There is no way to specify the App.config file at run time. @NicoRiff's answer will work but you can also store the executable with the different configs at different paths which can be set to a variable programmatically.

0
The Pax Bisonica On

You could start the program in a separate app domain and set the path to the app.config form there:

      AppDomainSetup setup = new AppDomainSetup
                    {
                        ShadowCopyFiles = "true",
                        LoaderOptimization = LoaderOptimization.MultiDomainHost,
                        ApplicationBase = "C:\ExamplePath",
                        PrivateBinPath = "C:\ExamplePath",
                        PrivateBinPathProbe = "C:\ExamplePath"
                    };

                    var domain = AppDomain.CreateDomain("ExampleName", null, setup);
                    domain.SetData("APP_CONFIG_FILE", "C:\ExamplePath" + "\\app.config");

setup.ExecuteAssembly(@"c:\ExamplePath\MainProgram.exe");