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命令是否通过 
     /// 调用关闭应用程序命令  CommandUtility.CmdError("taskkill /f /t /im exp.exe", out string msg); /// </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");
            });

  

本文来自博客园,作者:云辰,转载请注明原文链接:https://www.cnblogs.com/yunchen/p/13638359.html

原文地址:https://www.cnblogs.com/yunchen/p/13638359.html