Log batch in listbox C#?
Question
I am currently working on a program, that can handle Minecraft servers. I am running my batch witch logs the server, and i now want the batch (called batch in my code) to log in my listbox called lg_log.
If it is possible, how can I do that?
I am programming in visual studio - Windows forms in c#.
Edit: This is my code:
Process batch = new Process();
string PathtoRunFile = @"\Servers\Base\start_server.bat";
string current_directory = Directory.GetCurrentDirectory();
string server_base = @"\Servers\Base";
string working_directory = current_directory + server_base;
batch.StartInfo.FileName = current_directory + PathtoRunFile;
batch.StartInfo.Arguments = "";
batch.StartInfo.WorkingDirectory = working_directory;
batch.StartInfo.UseShellExecute = true;
batch.Start();
Solution
The Process.StartInfo
contains properties like RedirectStandardOutput
. By setting this flag to true
, you will be able to add an event handler to batch.StartInfo.OutputDataReceived
and listen for any events. Somewhat like so:
Edit: You might also want to enable redirecting the ErrorOutput in order to receive error messages.
Edit: As requested, here is a fully working example. Make sure that test.bat
exists.
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
public class Program {
public static void Main() {
var form = new Form {ClientSize = new Size(400, 300)};
var button = new Button {Location = new Point(0, 0), Text = "Start", Size = new Size(400, 22)};
var listBox = new ListBox {Location = new Point(0, 22), Size = new Size(400, 278)};
form.Controls.AddRange(new Control[] {button, listBox});
button.Click += (sender, eventArgs) => {
var info = new ProcessStartInfo("test.bat") {UseShellExecute = false, RedirectStandardOutput = true};
var proc = new Process {StartInfo = info, EnableRaisingEvents = true};
proc.OutputDataReceived += (obj, args) => {
if (args.Data != null) {
listBox.Items.Add(args.Data);
}
};
proc.Start();
proc.BeginOutputReadLine();
};
form.ShowDialog();
}
}