Reputation: 12705
in my project (MVC 3) I want to run an external console application using the following code:
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();
}
but I get an empty string in the returnvalue
and that program creates a file as a result but there is not any file created. Maybe taht Process
is not being executed ?
Upvotes: 2
Views: 1324
Reputation: 20157
If I recall correctly, to read both standard error and standard output at the same time, you must do it with an async callback:
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();
}
Upvotes: 3
Reputation:
You have to wait for your external program to finish otherwise the output you want to read is not even generated when you want to read it.
using (Process process = Process.Start(info))
{
if(process.WaitForExit(myTimeOutInMilliseconds))
{
StreamReader sr = process.StandardOutput;
returnvalue = sr.ReadToEnd();
}
}
Upvotes: 0
Reputation: 12705
as TimothyP said in the comment, after setting RedirectStandardError = true
and then via process.StandardError.ReadToEnd()
I get the error message content
Upvotes: 0