我有一个非常奇怪的问题,需要对 C# 的后台工作人员有深入的了解。
我想运行一个命令行程序并检查它的 ERRORLEVEL。
cmd.exe /c echo Launching the command && COMMAND_TO_RUN & echo Connexion statut : && echo %ERRORLEVEL% && if %ERRORLEVEL% NEQ 0 (echo FAILURE) ELSE (echo SUCCESS))
当命令失败时,ERRORLEVEL 得到值 -1
这在我在 cmd.exe 中使用此行时有效。
但是,这就是问题所在。
当我使用后台工作人员运行此行时,即使 COMMAND_TO_RUN 失败,ERRORLEVEL 的值也会为 0。
这是我的后台工作人员代码:
string[] args = { "/c echo Launching the command && COMMAND_TO_RUN & echo Connexion statut : && echo %ERRORLEVEL% && if %ERRORLEVEL% NEQ 0 (echo FAILURE) ELSE (echo SUCCESS))};
backgroundWorker1.RunWorkerAsync(args);
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string[] args = e.Argument as string[];
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = args[0];
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.Start();
System.IO.StreamReader sOut = process.StandardOutput;
string tempOut;
while (!sOut.EndOfStream)
{
// using the report progress userstate allow me to catch
// the program output in runtime
tempOut = sOut.ReadLine();
backgroundWorker1.ReportProgress(1, tempOut);
}
process.Close();
}
那么使用 backgroundworker 会导致 ERRORLEVEL 的特定值吗?
提前致谢