C#运行外部控制台应用程序,并没有ouptut?
问题描述:
在我的项目(MVC 3)我想用下面的代码运行外部控制台应用程序:C#运行外部控制台应用程序,并没有ouptut?
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
一个空字符串,该程序创建一个文件作为一个结果,但有没有创建任何文件。可能没有执行Process
?
答
您必须等待您的外部程序完成,否则当您想要读取它时,您想要读取的输出甚至不会生成。
using (Process process = Process.Start(info))
{
if(process.WaitForExit(myTimeOutInMilliseconds))
{
StreamReader sr = process.StandardOutput;
returnvalue = sr.ReadToEnd();
}
}
答
为TimothyP中的评论称,设置RedirectStandardError = true
,然后通过process.StandardError.ReadToEnd()
后,我得到错误信息内容
答
如果我没有记错,在同一时间阅读这两个标准错误和标准输出,必须使用异步回调来实现:
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();
}
是否可以通过管道将其输出为标准错误? – 2013-04-04 15:43:52
您的IIS apppool用户是否有足够的权利? – 2013-04-04 15:44:14
没有足够的信息。这里没有创建文件,你的问题也不清楚。 – 2013-04-04 15:45:58