C# 后台调用 CMD 执行命令
有时会在程序中调用系统的命令行工具 cmd.exe
来静默执行一些系统命令,然后获取返回值。本文将展示 .NET/C#
静默运行 cmd
并执行命令的方法,包括 有返回值
和 无返回值
两种。
无返回值
public static void Execute(string command)
{
var processInfo = new ProcessStartInfo("cmd.exe", "/S /C " + command)
{
CreateNoWindow = true,
UseShellExecute = true,
WindowStyle = ProcessWindowStyle.Hidden
};
Process.Start(processInfo);
}
有返回值
public static string ExecuteWithOutput(string command)
{
var processInfo = new ProcessStartInfo("cmd.exe", "/S /C " + command)
{
CreateNoWindow = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true
};
var process = new Process {StartInfo = processInfo};
process.Start();
var outpup = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return outpup;
}
想了解更多的参数解释,请访问源码:.NETUtilities - CmdRunner - GitHub