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 = "format.com";
            p.StartInfo.Arguments = " G: /FS:FAT /Q";
            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;
 
            p.Exited += new EventHandler(p_Exited);
            p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
            p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
 
            p.Start();
            p.StandardInput.WriteLine("");
            p.StandardInput.WriteLine("");
 
            //开始异步读取输出
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
 
            //调用WaitForExit会等待Exited事件完成后再继续往下执行。
            p.WaitForExit();
            p.Close();
             
            Console.WriteLine("exit");
 
        }
 
        void p_OutputDataReceived(Object sender, DataReceivedEventArgs e)
        {
            //这里是正常的输出
            Console.WriteLine(e.Data);
 
        }
 
        void p_ErrorDataReceived(Object sender, DataReceivedEventArgs e)
        {
            //这里得到的是错误信息
            Console.WriteLine(e.Data);
 
        }
 
        void p_Exited(Object sender, EventArgs e)
        {
            Console.WriteLine("finish");
        }
 
    }
}
复制代码

 

posted @   遥望星空  阅读(3908)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2008-08-13 DiscuzNT改造-远程内容自动采集-DNT2.5(定时采集、源码下载)
点击右上角即可分享
微信分享提示