我想使用以下C#方法以编程方式为自动化进程构建我的Angular 8应用程序。
private bool RunBuildProd(string angularAppFolder)
{
try
{
ProcessStartInfo objPI = new ProcessStartInfo(@"C:Program FilesNodejsnpm.cmd", $"run build");
// ProcessStartInfo objPI = new ProcessStartInfo(@"cmd.exe", $"/c npm run build"); // Also tried this one
objPI.WorkingDirectory = angularAppFolder;
objPI.RedirectStandardError = true;
objPI.RedirectStandardOutput = true;
objPI.UseShellExecute = false;
objPI.CreateNoWindow = true;
objPI.WindowStyle = ProcessWindowStyle.Hidden;
Process objProcess = Process.Start(objPI);
string error = objProcess.StandardError.ReadToEnd();
string output = objProcess.StandardOutput.ReadToEnd();
objProcess.WaitForExit();
return (objProcess.ExitCode == 0);
}
catch (Exception ex)
{
return false;
}
}
在执行上述方法时,我面临两个问题:
- 当运行下面的方法时,它不会在dist文件夹下生成index.html文件注意:如果我运行"npm运行构建";命令,它会直接生成index.html
- 它在很长一段时间内都不会退出这个过程,我不得不杀死它
我缺少什么?如何解决?
注意:我已经运行了"npm安装";在运行上述方法之前。
UPDATE:以下是基于Serg的答案更新的代码,用于避免stdout&stderr。。。
private bool RunBuildProd(string angularAppFolder)
{
try
{
// ProcessStartInfo objPI = new ProcessStartInfo(@"cmd.exe", $"/c npm run build"); // Also tried this one
ProcessStartInfo objPI = new ProcessStartInfo(@"C:Program FilesNodejsnpm.cmd", $"run build");
objPI.WorkingDirectory = angularAppFolder;
objPI.RedirectStandardError = true;
objPI.RedirectStandardOutput = true;
objPI.UseShellExecute = false;
objPI.CreateNoWindow = true;
objPI.WindowStyle = ProcessWindowStyle.Hidden;
StringBuilder sbOutput = new StringBuilder();
StringBuilder sbError = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
Process objProcess = Process.Start(objPI);
objProcess.OutputDataReceived += (sender, e) =>{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
sbOutput.AppendLine(e.Data);
}
};
objProcess.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
sbError.AppendLine(e.Data);
}
};
objProcess.BeginOutputReadLine();
objProcess.BeginErrorReadLine();
objProcess.WaitForExit();
int timeout = 42000;
if (outputWaitHandle.WaitOne(timeout) &&
errorWaitHandle.WaitOne(timeout))
{
// Process completed. Check process.ExitCode here.
return (objProcess.ExitCode == 0);
}
else
{
// Timed out.
return (objProcess.ExitCode == 0);
}
}
}
catch (Exception ex)
{
return false;
}
}
由于stdout&stderr。可能的解决方案可以在这里找到
- 重定向输出相对较大时启动的进程挂起
- ProcessStartInfo挂起";等待退出"?为什么
- http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx(备注部分(