c# process 输入、输出、捕获进程输出

以下代码是使用窗口程序测试的,同样适应于命令行程序。

复制代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = "ping";
            p.StartInfo.Arguments = "127.0.0.1";
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;//true表示不显示黑框,false表示显示dos界面 
            p.StartInfo.UseShellExecute = false;
 
            p.EnableRaisingEvents = true;//在进程终止时是否应引发 Process.Exited 事件
 
            p.OutputDataReceived += (s, ev) => { Console.WriteLine(ev.Data); };
            p.ErrorDataReceived += (s, ev) => { Console.WriteLine(ev.Data); };
            p.Exited += (s, ev) => { Console.WriteLine(ev.ToString()); };
 
            p.Start();
            p.StandardInput.WriteLine("");
            p.StandardInput.WriteLine("");
 
            //开始异步读取输出
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
 
            //调用WaitForExit会等待Exited事件完成后再继续往下执行。
            p.WaitForExit();
            p.Close();
             
            Console.WriteLine("exit");
 
        }
 
    }
}
复制代码

 

2024-08-19 16:22:31【出处】:https://www.cnblogs.com/Alex80/p/4961615.html

=======================================================================================

百度AI智能回答:c# Process输出

在C#中,可以使用System.Diagnostics.Process类来启动外部程序,并获取它的输出。以下是一个简单的示例,展示如何启动一个外部程序并捕获它的输出:

using System;
using System.Diagnostics;

class Program
{
static void Main()
{
ProcessStartInfo startInfo = new ProcessStartInfo("your-command-here", "arguments");
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;

using (Process process = Process.Start(startInfo))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd(); // 读取输出流
Console.WriteLine(result);
}

string error = process.StandardError.ReadToEnd(); // 读取错误流
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine("Error: " + error);
}

process.WaitForExit(); // 等待程序执行完成
}
}
}

替换your-command-here和arguments为你想要执行的外部程序名和它的参数。这段代码将会启动一个外部程序,并且捕获它的标准输出和标准错误流。输出将被打印到控制台,错误信息如果有的话也会被打印。

请确保外部程序的路径是正确的,否则这段代码可能无法正常工作。此外,如果外部程序需要管理员权限,你可能需要设置startInfo.Verb = "runas";。

 

=======================================================================================

 以上程序可以使用异步读取,请自行修改为异步读取的方式。

posted on 2024-08-19 16:27  jack_Meng  阅读(7)  评论(0编辑  收藏  举报

导航