using System.Diagnostics;
namespace cmd
{
/// <summary>
/// 调用cmd命令行
/// </summary>
public static class cmd
{
/// <summary>
/// 发命令
/// </summary>
/// <param name="commandLine"></param>
/// <returns></returns>
public static string Cmd(string commandLine)
{
commandLine = commandLine.Trim().TrimStart('&') + "&exit";//&执行两条命令的标识,这里第二条命令的目的是当调用ReadToEnd()方法是,不会出现假死状态
string outputMsg = "";
Process pro = new Process();
pro.StartInfo.FileName = "cmd.exe";//调用cmd.exe
pro.StartInfo.UseShellExecute = false;//是否启用shell启动进程
pro.StartInfo.RedirectStandardError = true;
pro.StartInfo.RedirectStandardInput = true;
pro.StartInfo.RedirectStandardOutput = true;//重定向的设置
pro.StartInfo.CreateNoWindow = true;//不创建窗口
pro.Start();
pro.StandardInput.WriteLine(commandLine);//执行cmd语句
pro.StandardInput.AutoFlush = true;
outputMsg+= pro.StandardOutput.ReadToEnd();//读取返回信息
//outputMsg=outputMsg.Substring(outputMsg.IndexOf(commandLine)+commandLine.Length);//返回发送命令之后的信息
pro.WaitForExit();//等待程序执行完退出,不过感觉不用这条命令,也可以达到同样的效果
pro.Close();
return outputMsg;
}
}
}
C#程序调用CMD执行命令 https://www.jianshu.com/p/68eadb85a662
Process 类 https://docs.microsoft.com/zh-cn/dotnet/api/system.diagnostics.process?view=net-6.0