Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new .Net Core Console Process: Exception when using environment variables with UseShellExecute=true

I want to run a number of .Net Core console apps from a single console. I have the following code:

        var startInfo = new ProcessStartInfo("c:\path\to\filename.exe", "arguments")
        {
            UseShellExecute = true,
            WorkingDirectory = "c:\working\directory",
        };
        var process = Process.Start(startInfo);

I receive the following exception: System.InvalidOperationException: 'The Process object must have the UseShellExecute property set to false in order to use environment variables.'

Apps use variables from appsettings.json file in WorkingDirectory.

How to run the app processes successfully, each in a separate console?

like image 391
user2341923 Avatar asked Oct 20 '25 05:10

user2341923


2 Answers

Since this is the top search result for the error message

The Process object must have the UseShellExecute property set to false in order to use environment variables

, I thought I would chime in with an observation after looking through reference source for EnvironmentVariables here and comparing to the use of the internal backing variable in ProcessStartInfo here.

Chances are, you're probably here because you're sitting in front of Visual Studio with a breakpoint trying to figure out what the right magic is to make UseShellExecute work.

If you look through the locals or immediate windows, or you serialize the ProcessStartInfo class object, or basically do anything that might directly or indirectly access ProcessStartInfo.EnvironmentVariables, the code will instantiate the collection and populate it! Then, when you actually try to start the process, the beginning part of the method throws out your config as invalid.

The only way to make UseShellExecute work is to ensure the environmentVariables backing field stays null, and to do that means, you can't access it any way (directly or indirectly).

like image 150
K0D4 Avatar answered Oct 21 '25 20:10

K0D4


This may help

var startInfo = new ProcessStartInfo("cmd.exe", @"/K ""c:\path\to\filename.exe"" arguments")
{
    UseShellExecute = false,
    WorkingDirectory = @"c:\working\directory",
    //CreateNoWindow = true
};
var process = Process.Start(startInfo);
like image 34
aepot Avatar answered Oct 21 '25 19:10

aepot