如何读取流程输出

本文关键字:输出 程输出 读取 何读取 | 更新日期: 2023-09-27 18:22:41

我试图创建一个minecraft服务器包装器,但在读取进程的输出时遇到了问题。我想读取serverProcess_ErrorDataRecevied事件中的输出,我知道现在的输出不起作用。但是,我可以放什么来代替阅读呢?

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)
        {
        }
    }
}

如何读取流程输出

参见:

  • 如何在.NET中生成进程并捕获其STDOUT
  • ProcessStartInfo.RedirectStandardOutput

代码:

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

或者:

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

另请参阅:ProcessStartInfo.RedirectStandardError

serverProcess.StartInfo.RedirectStandardError = true;
var error = serverProcess.StandardError.ReadToEnd();