0

Im trying to start CMD process from my program that starts another process that redirect output and errors into file. And I have to have exit code of this process.

var exe = pathToExe
var output = Path.GetTempFileName();
var process = Process.Start(new ProcessStartInfo
{
     FileName = "cmd",
     Arguments = $"/c "{exe} {command} > {output} 2<&1" & echo %errorlevel% > {output})", 
     Verb = "runas",
     UseShellExecute = true,
     CreateNoWindow = true,
     WindowStyle = ProcessWindowStyle.Hidden
});
                
process.WaitForExit();
var res = File.ReadAllText(output);
Console.WriteLine(res);

Same command (cmd /c "pathToExe command > output 2<&1" & echo %errorlevel% > output) worked fine in cmd, but in this code is errorlevel always 0 (I suggest its just errorlevel of cmd process)

At this point you may ask me why am I even using cmd to start process... Well, Ive tried

using (var process = CreateProcess(processName, argumnets))
{
    var error = 0;
    var output = Path.GetTempFileName();
    process.StartInfo.UseShellExecute = true;
    process.StartInfo.Verb = "runas";   
    process.StartInfo.Arguments = $"{command} > {output} 2<&1";
    process.Start();
    process.WaitForExit();
    statusInfo = File.ReadAllText(output);
    File.Delete(output);
    if (process.ExitCode != 0)
    {
        error = process.ExitCode;
    }
    return error;
}

But it didnt work for me. Also i cant redirect outputrs programmatically because of process.StartInfo.UseShellExecute.

0 Answers0