我有以下代码用于打开cmd并使用配置文件运行SQL Server setup.exe。
ProcessStartInfo pStartInfo = new ProcessStartInfo();
pStartInfo.FileName = "cmd.exe";
pStartInfo.Arguments = "/c /q setup.exe /c /q /configurationFile=../configurationFile.ini";
pStartInfo.WorkingDirectory = installDir + @"\SQL Server Unpacked";
pStartInfo.CreateNoWindow = true;
pStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
pStartInfo.UseShellExecute = false;
pStartInfo.RedirectStandardInput = true;
pStartInfo.RedirectStandardOutput = true;
pStartInfo.RedirectStandardError = true;
Process p = new Process();
p.StartInfo = pStartInfo;
lb_SQLServerReadout.Text = "Please wait while the setup runs";
p.Start();
这工作正常。它将尝试使用配置文件的详细信息进行安装,如果配置文件包含无效的详细信息,则setup.exe将发出错误而不安装。
我希望能够获取该错误代码并将其写入表单上的标签,因此用户可以通过某种方式了解错误发生的原因以及发生错误的原因。我考虑使用Process.StandardError.ReadToEnd
,但它始终会返回null
。我相信这是因为Process
本身是cmd,而不是setup.exe(实际发生错误的地方)。
我已经读过可以使用echo %errorlabel%
在cmd中获取最后一个错误代码,并且当我手动运行时它确实有效,所以我尝试在我的代码中实现它:
p.StandardInput.WriteLine("echo %errorlevel%");
string s = p.StandardOutput.ReadLine();
p.WaitForExit();
我希望将s
设置为echo %errorlevel%
输入的输出,但它只设置为null
。
如何通过我的cmd Process
?
正如旁注,我考虑将setup.exe作为Process
运行,但它需要提升,这意味着启用UseShellExecute
,这反过来意味着禁用RedirectStandardError
,这会阻止我得到错误代码。
答案 0 :(得分:1)
这一切都没有必要,"可执行文件的退出代码"使用cmd.exe /c
调用的是cmd.exe
本身的退出代码。
您也可以在命令行上尝试:
c:\> cmd.exe /c app.exe make-it-fail
c:\> echo %errorlevel%
第二行将打印退出代码" app.exe make-it-fail"。
因此,只需在Process.ExitCode
之后阅读Process.WaitForExit()
属性的值。
setup.exe
(SQL Server)的特定值设置如果失败,我不知道。应该是不同于0
的东西(按惯例)。