0

Im trying to create a minecraft server wrapper but im having trouble reading the output of the process. I want to read the output in the serverProcess_ErrorDataRecevied event and I know that what there is now doesn't work. But what could I put there instead to read it?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace MC_Server_UI
{
    public partial class Form1 : Form
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("C:\\Program Files (x86)\\Java\\jre7\\bin\\java.exe", "Xmx1024M - jar " + "craftbukkit.jar" + " nogui");
        Process serverProcess;

        OpenFileDialog ofd;
        FolderBrowserDialog fbd;

        public Form1()
        {
            InitializeComponent();

            fbd = new FolderBrowserDialog();
            fbd.ShowDialog();

            startInfo.WorkingDirectory = fbd.SelectedPath;
            startInfo.RedirectStandardInput = startInfo.RedirectStandardError = true;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;

            serverProcess = new Process();
            serverProcess.StartInfo = startInfo;
            serverProcess.EnableRaisingEvents = true;
            serverProcess.ErrorDataReceived += new DataReceivedEventHandler(serverProcess_ErrorDataReceived);
            serverProcess.Exited += new EventHandler(serverProcess_Exited);
            serverProcess.Start();
        }

        private void serverProcess_ErrorDataReceived(object sender, EventArgs e)
        {
            richTextBox1.AppendText(serverProcess.StandardError.ReadToEnd());
        }

        private void serverProcess_Exited(object sender, EventArgs e)
        {

        }
    }
}

1 Answers1

0

See:

Code:

serverProcess.StartInfo.RedirectStandardOutput = true;
serverProcess.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
serverProcess.Start();
serverProcess.BeginOutputReadLine();

Or:

serverProcess.StartInfo.RedirectStandardOutput = true;
var output = serverProcess.StandardOutput.ReadToEnd();

See also: ProcessStartInfo.RedirectStandardError

serverProcess.StartInfo.RedirectStandardError = true;
var error = serverProcess.StandardError.ReadToEnd();
Community
  • 1
  • 1
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • I don't see how that answers my question. I have redirected the streams and using .ReadToEnd doesn't work. –  Jul 16 '13 at 13:59
  • The `StandardError` and `StandardOutput` is a `StreamReader`. You can use that to pull output from the process. The `OutputDataReceived` is an event that will also work. – Dustin Kingen Jul 16 '13 at 14:07
  • After some testing I notice that the event will only trigger if I have done .BeginErrorReadLine but using .ReadToEnd will then throw an exception. –  Jul 16 '13 at 14:28