写的东西用到了执行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