第一种返回命令执行后的结果,顺便加上解释
static string StartCmd(string cmd)
{
if (cmd == string.Empty || cmd == "") return null;
try
{
using (Process p = new Process())
{
string output = null;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine(cmd + "&exit");
output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
}
catch(Exception ex)
{
return ex.Message;
}
}
第二种是没有返回值的,直接执行命令,但是要通过一个异步事件来获得得到的结果。如果直接读取不退出,即没有exit时,会阻塞UI,直接造成程序假死。所以要不就是等读取完后退出,要不然就单独开启一个县城来执行startcmd。在这里是直接使用异步读取事件,不用自己创建线程。
public void startcmd(string command)
{
try
{
Process cmd = new Process()
cmd.StartInfo.FileName = "cmd.exe"
cmd.StartInfo.Arguments = "/c" + command
cmd.StartInfo.UseShellExecute = false
cmd.StartInfo.RedirectStandardInput = true
cmd.StartInfo.RedirectStandardOutput = true
cmd.StartInfo.CreateNoWindow = true
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
cmd.OutputDataReceived += new DataReceivedEventHandler(CmdOutputHandler)
cmd.Start()
cmd.BeginOutputReadLine()
cmd.StandardInput.WriteLine(command)
cmd.WaitForExit()
cmd.Close()
}
catch (Exception e)
{
Console.WriteLine("Error" + e.Message)
}
}
private void CmdOutputHandler(object sendingProcess,DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
ListAdd(outLine.Data)
}
}