1. 程式人生 > 實用技巧 >C# 控制檯CMD輔助類

C# 控制檯CMD輔助類

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using GH.Commons.Log;

namespace OracleImpExp.Utilities
{
    /// <summary>
    /// 控制檯輔助類
    /// </summary>
    public static class CommandUtility
    {       
        /// <summary>
        /// 在控制檯中執行命令。(阻塞、非同步讀取輸出)
        /// </summary>
        /// <param name="commonds">命令</param>
        /// <param name="callBack">輸出回撥</param>
        /// <param name="workingDirectory">工作目錄</param>
        /// <param name="outputEncoding">輸出編碼</param>
        public static void Execute2(List<string> commonds, Action<string> callBack = null, string workingDirectory = "", Encoding outputEncoding = null)
        {
            Process process = new Process();
            process.StartInfo.FileName = @"cmd.exe";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            if (outputEncoding != null)
                process.StartInfo.StandardOutputEncoding = outputEncoding;
            if (!string.IsNullOrWhiteSpace(workingDirectory))
                process.StartInfo.WorkingDirectory = workingDirectory;
            process.OutputDataReceived += (sender, e) =>
            {
                if (e.Data != null) callBack?.Invoke(e.Data);
            };
            process.ErrorDataReceived += (sender, e) =>
            {
                if (e.Data != null) callBack?.Invoke(e.Data);
            };

            if (process.Start())
            {
                process.BeginErrorReadLine();
                process.BeginOutputReadLine();

                StreamWriter input = process.StandardInput;
                input.AutoFlush = true;

                foreach (string command in commonds)
                {
                    input.WriteLine(command);
                }
                input.WriteLine(@"exit");

                process.WaitForExit();
                process.Close();
            }
        }

        /// <summary>
        /// 在控制檯中執行命令。(阻塞、非同步讀取輸出)
        /// </summary>
        /// <param name="command">命令</param>
        /// <param name="callBack">輸出回撥</param>
        /// <param name="workingDirectory">工作目錄</param>
        /// <param name="outputEncoding">輸出編碼</param>
        public static void Execute2(string command, Action<string> callBack = null, string workingDirectory = "", Encoding outputEncoding = null)
        {
            Execute2(new List<string> { command }, callBack, workingDirectory, outputEncoding);
        }

        /// <summary>
        /// 檢測CMD命令是否通過
        /// </summary>
        /// <param name="command">CMD命令</param>
        /// <returns></returns>
        public static bool CmdError(string command, out string msg)
        {
            bool flag = true;
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.AutoFlush = true;
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
            p.StandardInput.Close();
            msg = p.StandardError.ReadToEnd();
            if (!string.IsNullOrEmpty(msg))
            {
                flag = false;  //自定義Bool,如果為真則表示CMD命令出錯
            }
            p.WaitForExit();
            p.Close();
            return flag;
        }

        /// <summary>   
        /// 關閉程序   
        /// </summary>   
        /// <param name="ProcName">程序名稱</param>   
        /// <returns></returns>   
        public static bool CloseProcess(string ProcName)
        {
            bool result = false;
            try
            {
                System.Collections.ArrayList procList = new System.Collections.ArrayList();
                string tempName = "";
                int begpos;
                int endpos;
                foreach (System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses())
                {
                    tempName = thisProc.ToString();
                    begpos = tempName.IndexOf("(") + 1;
                    endpos = tempName.IndexOf(")");
                    tempName = tempName.Substring(begpos, endpos - begpos);
                    procList.Add(tempName);
                    if (tempName == ProcName)
                    {
                        if (!thisProc.CloseMainWindow())
                            thisProc.Kill(); // 當傳送關閉視窗命令無效時強行結束程序   
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                log4NetUtil.Error(ex);
                result = false;
            }
            return result;
        }


    }
}

  

呼叫方法:

      /// <summary>
        /// 正在工作
        /// </summary>
        bool IsWorking
        {
            get { return isWorking; }
            set
            {
                ChangeControlEnabled(!value);
                isWorking = value;
            }
        }

  

     /// <summary>
        /// 更新介面
        /// </summary>
        /// <param name="action"></param>
        private void UpdateUIInThread(Action action)
        {
            if (this.Disposing || this.IsDisposed) return;

            if (this.InvokeRequired)
                this.Invoke(action);
            else
                action();
        }

  

     /// <summary>
        /// 啟用/禁用介面操作
        /// </summary>
        /// <param name="enabled"></param>
        private void ChangeControlEnabled(bool enabled)
        {
            UpdateUIInThread(() =>
            {
                BtnOpenFile.Enabled = enabled;
                TxtfoldPath.Enabled = enabled;
                TxtHostIP.Enabled = enabled;
                TxtAccount.Enabled = enabled;
                TxtPwd.Enabled = enabled;
                TxtServer.Enabled = enabled;
                BtnExport.Enabled = enabled;
                BtnSave.Enabled = enabled;

                //timer.Enabled = enabled;
            });
        }

  

       this.IsWorking = true;

            Task task = new Task(() =>
            {
                CommandUtility.Execute2(command, a =>
                {
                    UpdateUIInThread(() => richTextBoxOutputer.AppendText(a));
                });
            });

            task.Start();

            task.ContinueWith((a) =>
            {
                this.IsWorking = false;
                UpdateUIInThread(() => richTextBoxOutputer.AppendText("匯出完成"));
                CommandUtility.CloseProcess("cmd.exe");
            });