运行 一个进程在后台默默地没有任何 window

Run a Process silently in background without any window

我想 运行 NETSH 命令静默(没有 window)。 我写了这段代码,但它不起作用。

public static bool ExecuteApplication(string Address, string workingDir, string arguments, bool showWindow)
{
    Process proc = new Process();
    proc.StartInfo.FileName = Address;
    proc.StartInfo.WorkingDirectory = workingDir;
    proc.StartInfo.Arguments = arguments;
    proc.StartInfo.CreateNoWindow = showWindow;
    return proc.Start();
}

string cmd= "interface set interface name=\"" + InterfaceName+"\" admin=enable";
ExecuteApplication("netsh.exe","",cmd, false);

让用户shell执行false

proc.StartInfo.UseShellExecute = false;

并在 showWindow 参数中传递 true

ExecuteApplication("netsh.exe","",cmd, true);

这是我在我的一个项目中的做法:

ProcessStartInfo psi = new ProcessStartInfo();            
psi.FileName = "netsh";            
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.Arguments = "SOME_ARGUMENTS";

Process proc = Process.Start(psi);                
proc.WaitForExit();
string errorOutput = proc.StandardError.ReadToEnd();
string standardOutput = proc.StandardOutput.ReadToEnd();
if (proc.ExitCode != 0)
    throw new Exception("netsh exit code: " + proc.ExitCode.ToString() + " " + (!string.IsNullOrEmpty(errorOutput) ? " " + errorOutput : "") + " " + (!string.IsNullOrEmpty(standardOutput) ? " " + standardOutput : ""));

它还考虑了命令的输出。