1. 程式人生 > >winform中執行cmd命令幫助類,提取有效輸出資料、錯誤返回資料與實時顯示命令輸出(可傳參)

winform中執行cmd命令幫助類,提取有效輸出資料、錯誤返回資料與實時顯示命令輸出(可傳參)

寫的東西用到了執行cmd命令,於是自己擴充寫了個幫助類,實時顯示命令輸出可能對大家最為有用,此方法與網上流傳的不同點在於可以在命令輸出完成後回撥,可傳入一個object型別的引數。

程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;

namespace tp7309.Winform
{
    /// <summary>
    /// Winform操作cmd的輔助類
    /// </summary>
    class CmdHelper
    {
        public string WorkPath { get; set; }
        /// <summary>
        /// 例項化CmdHelper 
        /// </summary>
        /// <param name="workPath">要切換到的工作目錄</param>
        public CmdHelper(string workPath)
        {
            this.WorkPath = workPath;
        }

        /// <summary>
        /// 得到cmd執行後輸出的錯誤。
        /// </summary>
        /// <param name="strCmd">需執行的cmd命令</param>
        /// <returns>cmd錯誤輸出的流</returns>
        public string GetCmdError(string strCmd)
        {
            Process proc = new Process
            {
                StartInfo =
                {
                    FileName = "cmd.exe",
                    UseShellExecute = false,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };
            proc.Start();
            if (this.WorkPath != null)
            {
                strCmd = "cd/d " + this.WorkPath + " & " + strCmd;
            }
            proc.StandardInput.WriteLine(strCmd);
            proc.StandardInput.WriteLine("exit");
            string strResult = proc.StandardError.ReadToEnd().Trim();
            proc.Close();
            return strResult;
        }

        /// <summary>
        /// 得到cmd執行命令後的有效輸出。
        /// </summary>
        /// <param name="strCmd">需執行的cmd命令</param>
        /// <returns>cmd執行命令後的有效輸出。</returns>
        public string GetCmdEffectiveOutput(string strCmd)
        {
            Process proc = new Process
            {
                StartInfo =
                {
                    FileName = "cmd.exe",
                    UseShellExecute = false,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };
            proc.Start();
            string guid1 = "{86F920F4-9061-4609-911E-6D3A1D7AFFB2}";   //有效行前導符
            string guid2 = "{589D5772-672E-4670-9D9B-DE67B79AD09C}";  //有效行後置符
            string strFullCmd = "echo " + guid1 + " & " + strCmd + " & echo " + guid2;    //附加分界符
            if (this.WorkPath != null)
            {
                strCmd = "cd/d " + this.WorkPath + " & " + strFullCmd;
            }
            proc.StandardInput.WriteLine(strFullCmd);
            proc.StandardInput.WriteLine("exit");
            string strFullOutput = proc.StandardOutput.ReadToEnd();
            string strOutput = "";
            strOutput = strFullOutput;
            int intGuid1After = strFullOutput.IndexOf(guid1, strFullOutput.IndexOf(guid1) + guid1.Length) + guid1.Length;
            int intGuid2Before = strFullOutput.LastIndexOf(guid2);
            strOutput = strFullOutput.Substring(intGuid1After, intGuid2Before - intGuid1After).Trim();
            proc.Close();
            return strOutput;
        }

        private Process proc = null;
        private TextBoxBase txtEditor;
        private delegate void AddMessageHandler(string msg);
        public delegate void CmdCallbackEventHandler(object obj);
        public event CmdCallbackEventHandler cmdCallBack;
        private object cmdFuncObj;
        private bool noData = true;
        private string currCmdStr = "";
        /// <summary>
        /// 獲取命令的實時輸出
        /// </summary>
        /// <param name="strCmd">需執行的命令</param>
        /// <param name="txt1">要實時顯示命令返回結果的繼承自TextBoxBase的控制元件(如TextBox、RichTextBox等)</param>
        /// <param name="func">命令實時顯示完成後要執行的函式</param>
        /// <param name="funcParamObj">命令實時顯示完成後要執行的函式的引數</param>
        public void GetRTOutput(string strCmd, TextBoxBase txt1, CmdCallbackEventHandler func, object funcParamObj)
        {
            if (func != null)
            {
                cmdCallBack += func;
                cmdFuncObj = funcParamObj;
            }
            else
            {
                cmdCallBack = null;
                cmdFuncObj = null;
            }
            noData = true;
            currCmdStr = strCmd;

            txtEditor = txt1;
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
            psi.FileName = "cmd.exe";
            if (this.WorkPath != null)
            {
                strCmd = "cd/d " + this.WorkPath + " & " + strCmd;
            }
            string guidSucc = "{9810A03C-5A90-43D3-BF60-492A418098CE}";
            psi.Arguments = "/c " + strCmd + " & echo " + guidSucc;    //或者不用重定向StandardInput直接在這裡加執行引數。
            psi.UseShellExecute = false;
            //psi.RedirectStandardInput = true;
            psi.RedirectStandardOutput = true;
            psi.CreateNoWindow = true;

            proc = new System.Diagnostics.Process();
            proc.StartInfo = psi;
            //定義接收訊息的Handler
            proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_OutputDataReceived);

            proc.Start();
            //proc.StandardInput.WriteLine(strCmd + " & echo " + guidSucc);
            //開始接收
            proc.BeginOutputReadLine();
        }

        private void p_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (!String.IsNullOrEmpty(e.Data))
            {
                string guidSucc = "{9810A03C-5A90-43D3-BF60-492A418098CE}";
                if (e.Data.Trim() == guidSucc)
                {
                    if (noData)   //解決有時實時接收的資料不準確的問題
                    {
                        AddMessageHandler handler = delegate(string msg)
                        {
                            txtEditor.Text += this.GetCmdEffectiveOutput(currCmdStr) + Environment.NewLine;
                            txtEditor.Select(txtEditor.Text.Length - 1, 0);
                            txtEditor.ScrollToCaret();
                        };
                        if (txtEditor.InvokeRequired)
                        {
                            txtEditor.Invoke(handler, e.Data);
                        }
                        else
                        {
                            txtEditor.Text += this.GetCmdEffectiveOutput(currCmdStr) + Environment.NewLine;
                            txtEditor.Select(txtEditor.Text.Length - 1, 0);
                            txtEditor.ScrollToCaret();
                        }
                    }
                    if (cmdCallBack != null)
                    {
                        cmdCallBack(cmdFuncObj);
                    }
                }
                else
                {
                    noData = false;
                    AddMessageHandler handler = delegate(string msg)
                    {
                        txtEditor.Text += msg + Environment.NewLine;
                        txtEditor.Select(txtEditor.Text.Length - 1, 0);
                        txtEditor.ScrollToCaret();
                    };
                    if (txtEditor.InvokeRequired)
                    {
                        txtEditor.Invoke(handler, e.Data);
                    }
                    else
                    {
                        txtEditor.Text += e.Data + Environment.NewLine;
                        txtEditor.Select(txtEditor.Text.Length - 1, 0);
                        txtEditor.ScrollToCaret();
                    }
                }
            }
        }
    }
}
呼叫:
            CmdHelper cmdHelper = new CmdHelper(null);
            string str1 = cmdHelper.GetCmdEffectiveOutput("dir/a");
            string str2 = cmdHelper.GetCmdError("java");
            cmdHelper.GetRTOutput("ping/n 3 192.168.33.44", txtEditor, new CmdHelper.CmdCallbackEventHandler(func1), "實時顯示已完成!");

        private void func1(object obj)
        {
            MessageBox.Show(obj.ToString());
        }


轉載請註明出處:http://blog.csdn.net/tp7309/article/details/9258603