Run a Process silently in background without any window

11,416

Solution 1

This is how I do it in a project of mine:

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 : ""));

It also accounts for the outputs of the command.

Solution 2

Make user shell execution false

proc.StartInfo.UseShellExecute = false;

and pass true in showWindow parameter

ExecuteApplication("netsh.exe","",cmd, true);
Share:
11,416
Dr developer
Author by

Dr developer

Updated on June 04, 2022

Comments

  • Dr developer
    Dr developer almost 2 years

    I want to run NETSH command silently (with no window). I wrote this code but it does not work.

    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);
    
  • Breeze
    Breeze almost 5 years
    It would also be helpful to change the behaviour inside ExecuteApplication. The showWindow parameter currently does the exact opposite of what it's name indicates.