在我的项目中(MVC 3)我想使用以下代码运行外部控制台应用程序:
string returnvalue = string.Empty;
ProcessStartInfo info = new ProcessStartInfo("C:\\someapp.exe");
info.UseShellExecute = false;
info.Arguments = "some params";
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
using (Process process = Process.Start(info))
{
StreamReader sr = process.StandardOutput;
returnvalue = sr.ReadToEnd();
}
但我在returnvalue
中得到一个空字符串,该程序创建了一个文件,但没有创建任何文件。也许taht Process
没有被执行?
答案 0 :(得分:1)
您必须等待外部程序完成,否则当您想要阅读时,甚至不会生成您想要阅读的输出。
using (Process process = Process.Start(info))
{
if(process.WaitForExit(myTimeOutInMilliseconds))
{
StreamReader sr = process.StandardOutput;
returnvalue = sr.ReadToEnd();
}
}
答案 1 :(得分:1)
如果我没记错,要同时读取标准错误和标准输出,必须使用异步回调:
var outputText = new StringBuilder();
var errorText = new StringBuilder();
string returnvalue;
using (var process = Process.Start(new ProcessStartInfo(
"C:\\someapp.exe",
"some params")
{
CreateNoWindow = true,
ErrorDialog = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false
}))
{
process.OutputDataReceived += (sendingProcess, outLine) =>
outputText.AppendLine(outLine.Data);
process.ErrorDataReceived += (sendingProcess, errorLine) =>
errorText.AppendLine(errorLine.Data);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
returnvalue = outputText.ToString() + Environment.NewLine + errorText.ToString();
}
答案 2 :(得分:0)
正如TimothyP在评论中所述,在设置RedirectStandardError = true
然后通过process.StandardError.ReadToEnd()
后,我收到错误消息内容