Tony
Tony

Reputation: 12705

C# Run external console application and no ouptut?

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

Answers (3)

Jesse C. Slicer
Jesse C. Slicer

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

user1064248
user1064248

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

Tony
Tony

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

Related Questions