Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

c# - Get exitcode from Process via arguments

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...