Question

hi i'm trying to build a parser for my System to Manage my Tekkit Server i am using C# but i have RedirectStandardOutput on my Tekkit Server process and there is a method set-up to then send that output to my console after adding to a List but it's not adding to a List<string>

Here is my code:

public void StartServer(string maxMem, string minMem, string path)
{
    ThreadStart server = new ThreadStart(delegate() { StartServerThread(maxMem, minMem, path); });
    server.Invoke();
}

private void StartServerThread(string maxMem, string minMem, string TekkitPath)
{
    try
    {
        TekkitServer.StartInfo.FileName = "java";
        TekkitServer.StartInfo.Arguments = String.Format("-Xmx{0} -Xms{1} -jar \"" + TekkitPath + "\" -nojline nogui", maxMem, minMem);
        TekkitServer.StartInfo.UseShellExecute = false;
        TekkitServer.StartInfo.RedirectStandardInput = true;
        TekkitServer.StartInfo.RedirectStandardOutput = true;
        TekkitServer.OutputDataReceived += new DataReceivedEventHandler(TekkitServer_OutputDataReceived);

        IsStarted = TekkitServer.Start();
        TekkitServerInput = TekkitServer.StandardInput;
    }
    catch (Exception)
    {
    }
}

void TekkitServer_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    /*B*/recordedData.Add(e.Data);
    Console.Out.WriteLine(e.Data);
}

Where /*B*/ is a break point, the breakpoint is never activating

Was it helpful?

Solution

By default, the standard output is directed at the console window.
If you need to do something with it, you need to redirect it, hence, you need to set RedirectStandardOutput = true; for the event to be fired.


Edit: This is my working code (with error handling and logging omitted):

public int ExecuteCommand(CommandParameters parameters)
{
  Process process = new Process();
  process.StartInfo.RedirectStandardInput = true;
  process.StartInfo.RedirectStandardOutput = true;
  process.StartInfo.RedirectStandardError = true;
  process.OutputDataReceived += StdOutputHandler;
  process.ErrorDataReceived += StdErrorHandler;
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.FileName = ...;
  process.StartInfo.Arguments = ...;
  process.Start();
  process.BeginErrorReadLine();
  process.BeginOutputReadLine();
  process.WaitForExit(parameters.Timeout);
  return process.ExitCode;
}

private void StdOutputHandler(object sendingProcess, DataReceivedEventArgs outdata)
{
  if (!string.IsNullOrEmpty(outdata.Data))
  {
    OutputMessages.Add(outdata.Data);
  }
}

Most likely the missing link in your code is the BeginOutputReadLine that actually gets the handler method on it's way.

Also, I use a fresh Process object and that I wait on it to finish it's job, so no interference with previous calls is possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top