一个Cmd命令运行工具类,这是一个核心的基础工具,在对apk进行反编译、回编译等操作时,都是通过执行相关的命令进行的,而执行这些命令就要靠这个工具。IngoreError
是一个痛点,当时一直没有找到更好的解决方法。实现代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace Com.Popotu.ApkIDE
{
/// <summary>
/// Cmd命令运行工具
/// </summary>
class ShellCmd
{
private string result;
private string errinf;
private Process process;
private bool disposed;
public ShellCmd() { disposed = false; }
/// <summary>
/// 是否忽略错误流(true可防卡死,但拿不到可能有的错误信息)
/// </summary>
public bool IngoreError { get; set; }
/// <summary>
/// 获取命令运行后的结果(包括全部命令行)
/// </summary>
public string Result { get { return result; } }
/// <summary>
/// 获取命令运行后的错误信息(如果有)
/// </summary>
public string Errinf { get { return errinf; } }
/// <summary>
/// 是否释放了
/// </summary>
public bool Disposed { get { return disposed; } }
/// <summary>
/// 强制中止
/// </summary>
public void Dispose()
{
if (process != null && !process.HasExited)
{
process.Kill();
process.Dispose();
disposed = true;
}
}
/// <summary>
/// 运行cmd命令
/// </summary>
/// <param name="cmds">命令组</param>
/// <param name="waitForExit">是否等待退出</param>
/// <param name="needResult">是否需要获取输出结果</param>
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
网友评论