【C#与Apk二三事】Cmd命令运行工具

一个Cmd命令运行工具类,这是一个核心的基础工具,在对apk进行反编译、回编译等操作时,都是通过执行相关的命令进行的,而执行这些命令就要靠这个工具。IngoreError是一个痛点,当时一直没有找到更好的解决方法。实现代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Com.Popotu.ApkIDE
{
    /// 
    /// Cmd命令运行工具
    /// 
    class ShellCmd
    {
        private string result;
        private string errinf;
        private Process process;
        private bool disposed;

        public ShellCmd() { disposed = false; }

        /// 
        /// 是否忽略错误流(true可防卡死,但拿不到可能有的错误信息)
        /// 
        public bool IngoreError { get; set; } 
        /// 
        /// 获取命令运行后的结果(包括全部命令行)
        /// 
        public string Result { get { return result; } }
        /// 
        /// 获取命令运行后的错误信息(如果有)
        /// 
        public string Errinf { get { return errinf; } }
        /// 
        /// 是否释放了
        /// 
        public bool Disposed { get { return disposed; } }
        /// 
        /// 强制中止
        /// 
        public void Dispose()
        {
            if (process != null && !process.HasExited)
            {
                process.Kill();
                process.Dispose();
                disposed = true;
            }
        }
        /// 
        /// 运行cmd命令
        /// 
        /// 命令组
        /// 是否等待退出
        /// 是否需要获取输出结果
        public void Run(string[] cmds, bool waitForExit=true, bool needResult=true)
        {
            result = errinf = string.Empty;
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "cmd.exe";
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = IngoreError ? false : true;
            startInfo.CreateNoWindow = true;
            //startInfo.Verb = "runas";
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process = Process.Start(startInfo);
            StreamWriter input = process.StandardInput;
            StreamReader output = process.StandardOutput;
            StreamReader error = null;
            if(!IngoreError) error = process.StandardError;
            foreach (string cmd in cmds)
            {
                input.WriteLine(cmd);
                input.Flush();
            }
            input.Close();
            if (needResult) result = output.ReadToEnd();
            output.Close();
            if (!IngoreError)
            {
                errinf = error.ReadToEnd();
                error.Close();
            }
            if(waitForExit) process.WaitForExit();
            process.Close();
        }
    }
}

by Mandarava(鳗驼螺) 2017.06.19

你可能感兴趣的:(【C#与Apk二三事】Cmd命令运行工具)