C#中运行命令行截取输出流的例子

 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Diagnostics;
  9. using System.IO;
  10. namespace RunCMD
  11. {
  12.     /**
  13.      * 作者:周公
  14.      * blog:http://blog.csdn.net/zhoufoxcn
  15.      * 日期:2007-07-07
  16.      * 
  17.      * */
  18.     public partial class CMDForm : Form
  19.     {
  20.         public CMDForm()
  21.         {
  22.             InitializeComponent();
  23.         }
  24.         private void btnExecute_Click(object sender, EventArgs e)
  25.         {
  26.             tbResult.Text = "";
  27.             ProcessStartInfo start = new ProcessStartInfo("Ping.exe");//设置运行的命令行文件问ping.exe文件,这个文件系统会自己找到
  28.             //如果是其它exe文件,则有可能需要指定详细路径,如运行winRar.exe
  29.             start.Arguments = txtCommand.Text;//设置命令参数
  30.             start.CreateNoWindow = true;//不显示dos命令行窗口
  31.             start.RedirectStandardOutput = true;//
  32.             start.RedirectStandardInput = true;//
  33.             start.UseShellExecute = false;//是否指定操作系统外壳进程启动程序
  34.             Process p=Process.Start(start);
  35.             StreamReader reader = p.StandardOutput;//截取输出流
  36.             string line = reader.ReadLine();//每次读取一行
  37.             while (!reader.EndOfStream)
  38.             {
  39.                 tbResult.AppendText(line+" ");
  40.                 line = reader.ReadLine();
  41.             }
  42.             p.WaitForExit();//等待程序执行完退出进程
  43.             p.Close();//关闭进程
  44.             reader.Close();//关闭流
  45.         }
  46.     }
  47. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值