Skip to content

Instantly share code, notes, and snippets.

@lindexi
Last active July 6, 2018 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lindexi/f2868a0d02f2197fbb62368514ed6f99 to your computer and use it in GitHub Desktop.
Save lindexi/f2868a0d02f2197fbb62368514ed6f99 to your computer and use it in GitHub Desktop.
private static (string output, int exitCode) Control(string str)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
p.StartInfo.CreateNoWindow = true; //不显示程序窗口
p.StartInfo.StandardOutputEncoding = Encoding.UTF8;//Encoding.GetEncoding("GBK");//乱码
p.Start(); //启动程序
//向cmd窗口发送输入信息
p.StandardInput.WriteLine(str + "&exit");
p.StandardInput.AutoFlush = true;
//向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
//同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令
//获取cmd窗口的输出信息
string output = p.StandardOutput.ReadToEnd();
output += p.StandardError.ReadToEnd();
p.WaitForExit(); //等待程序执行完退出进程
var ec = p.ExitCode;
p.Close();
return (output + "\r\n", ec);
}
private static (string output, int exitCode) Control(string str)
{
var processStartInfo = new ProcessStartInfo()
{
Verb = "runas", // 如果程序是管理员权限,那么运行 cmd 也是管理员权限
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = false, // 如果需要隐藏窗口,设置为 true 就不显示窗口
StandardOutputEncoding = Encoding.UTF8,
Arguments = "/K " + str + " &exit",
};
var p = Process.Start(processStartInfo);
//向cmd窗口发送输入信息
p.StandardInput.AutoFlush = true;
//向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
//同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令
//获取cmd窗口的输出信息
var output = "";
var task = p.StandardOutput.ReadToEndAsync();
task.Wait(2000);
if (task.IsCompleted)
{
output += task.Result;
}
task = p.StandardError.ReadToEndAsync();
task.Wait(2000);
if (task.IsCompleted)
{
output += task.Result;
}
Console.WriteLine(output);
p.WaitForExit(10000); //等待程序执行完退出进程
p.Close();
int ec = 0;
try
{
ec = p.ExitCode;
}
catch (Exception)
{
}
return (output + "\r\n", ec);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment