c#中重定向windows控制台程序的输出信息

本文介绍了一个使用 C# 实现的简单示例,该示例展示了如何通过调用外部命令(如 ipconfig)并实时显示其输出到应用程序界面上的方法。这种方法适用于需要实时查看复杂命令执行过程的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个问题来自论坛提问,答案如下.这只是一个简单的ipconfig命令.如果是复杂的,比如oracle的exp之类的命令,能在调用的时候显示出来,还是相当酷的.

using  System;
using  System.Windows.Forms;

namespace  WindowsApplication8
{
    
public   partial   class  Form1 : Form
    
{
        
public  Form1()
        
{
            InitializeComponent();
        }


        
delegate   void  dReadLine( string  strLine);
        
private   void  excuteCommand( string  strFile,  string  args, dReadLine onReadLine)
        
{
            System.Diagnostics.Process p 
=   new  System.Diagnostics.Process();
            p.StartInfo 
=   new  System.Diagnostics.ProcessStartInfo();
            p.StartInfo.FileName 
=  strFile;
            p.StartInfo.Arguments 
=  args;
            p.StartInfo.WindowStyle 
=  System.Diagnostics.ProcessWindowStyle.Hidden;
            p.StartInfo.RedirectStandardOutput 
=   true ;
            p.StartInfo.UseShellExecute 
=   false ;
            p.StartInfo.CreateNoWindow 
=   true ;
            p.Start();
            System.IO.StreamReader reader 
=  p.StandardOutput; // 截取输出流
             string  line  =  reader.ReadLine(); // 每次读取一行
             while  ( ! reader.EndOfStream)
            
{
                onReadLine(line);
                line 
=  reader.ReadLine();
            }

            p.WaitForExit();
        }


        
private   void  button1_Click( object  sender, EventArgs e)
        
{
            excuteCommand(
" ipconfig " "" new  dReadLine(PrintMessage));
        }

        
private   void  PrintMessage( string  strLine)
        
{
            
this .textBox1.Text  +=  strLine  +   " " ;
        }

    }

}
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值