c#運行程式回顯

來源:互聯網
上載者:User

說明:經常有朋友問如何在C#中運行一個dos命令,並截取輸出、輸出資料流的問題,這個問題我以前在Java中實現過,由於在C#中沒有遇到過類似的 情況,為了避免每次別人問都要一遍一遍示範的情況,特地做了一個簡單的例子,實現在WinForm中ping一個網站,並且將ping的結果顯示在一個文字框中。

運行結果圖

表單設計器產生的代碼:
namespace RunCMD
{
    partial class CMDForm
    {
        /// <summary>
        /// 必需的設計器變數。
        /// </summary>
        private System.ComponentModel.IContainer components = null ;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing"> 如果應釋放託管資源,為 true;否則為 false。 </param>
        protected override void Dispose( bool disposing)
        {
            if (disposing && (components != null ))
            {
                components.Dispose();
            }
            base .Dispose(disposing);
        }

        #region Windows 表單設計器產生的程式碼

        /// <summary>
        /// 設計器支援所需的方法 - 不要
        /// 使用代碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this .label1 = new System.Windows.Forms.Label();
            this .txtCommand = new System.Windows.Forms.TextBox();
            this .btnExecute = new System.Windows.Forms.Button();
            this .tbResult = new System.Windows.Forms.TextBox();
            this .SuspendLayout();
            //
            // label1
            //
            this .label1.AutoSize = true ;
            this .label1.Location = new System.Drawing.Point( 6 , 11 );
            this .label1.Name = " label1 " ;
            this .label1.Size = new System.Drawing.Size( 29 , 12 );
            this .label1.TabIndex = 0 ;
            this .label1.Text = " ping " ;
            //
            // txtCommand
            //
            this .txtCommand.Location = new System.Drawing.Point( 41 , 8 );
            this .txtCommand.Name = " txtCommand " ;
            this .txtCommand.Size = new System.Drawing.Size( 269 , 21 );
            this .txtCommand.TabIndex = 1 ;
            //
            // btnExecute
            //
            this .btnExecute.Location = new System.Drawing.Point( 316 , 6 );
            this .btnExecute.Name = " btnExecute " ;
            this .btnExecute.Size = new System.Drawing.Size( 75 , 23 );
            this .btnExecute.TabIndex = 2 ;
            this .btnExecute.Text = " 執行 " ;
            this .btnExecute.UseVisualStyleBackColor = true ;
            this .btnExecute.Click += new System.EventHandler( this .btnExecute_Click);
            //
            // tbResult
            //
            this .tbResult.Location = new System.Drawing.Point( 8 , 47 );
            this .tbResult.Multiline = true ;
            this .tbResult.Name = " tbResult " ;
            this .tbResult.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this .tbResult.Size = new System.Drawing.Size( 383 , 292 );
            this .tbResult.TabIndex = 3 ;
            //
            // CMDForm
            //
            this .AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this .AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this .ClientSize = new System.Drawing.Size( 403 , 364 );
            this .Controls.Add( this .tbResult);
            this .Controls.Add( this .btnExecute);
            this .Controls.Add( this .txtCommand);
            this .Controls.Add( this .label1);
            this .Name = " CMDForm " ;
            this .Text = " 運行Command的例子 " ;
            this .ResumeLayout( false );
            this .PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtCommand;
        private System.Windows.Forms.Button btnExecute;
        private System.Windows.Forms.TextBox tbResult;
    }
}


關鍵區段代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace RunCMD
{
    /* *
     * 作者:周公
     * blog: http://blog.csdn.net/zhoufoxcn
     * 日期:2007-07-07
     *
     * */
    public partial class CMDForm : Form
    {
        public CMDForm()
        {
            InitializeComponent();
        }

        private void btnExecute_Click( object sender, EventArgs e)
        {
            tbResult.Text = "" ;
            ProcessStartInfo start = new ProcessStartInfo( " Ping.exe " ); // 設定啟動並執行命令列檔案問ping.exe檔案,這個檔案系統會自己找到
            // 如果是其它exe檔案,則有可能需要指定詳細路徑,如運行winRar.exe
            start.Arguments = txtCommand.Text; // 設定命令參數
            start.CreateNoWindow = true ; // 不顯示dos命令列視窗
            start.RedirectStandardOutput = true ; //
            start.RedirectStandardInput = true ; //
            start.UseShellExecute = false ; // 是否指定作業系統外殼進程啟動程式
            Process p = Process.Start(start);
            StreamReader reader = p.StandardOutput; // 截取輸出資料流
            string line = reader.ReadLine(); // 每次讀取一行
            while ( ! reader.EndOfStream)
            {
                tbResult.AppendText(line + " " );
                line = reader.ReadLine();
            }
            p.WaitForExit(); // 等待程式執行完退出進程
            p.Close(); // 關閉進程
            reader.Close(); // 關閉流
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.