Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a Process silently in background without any window

Tags:

c#

process

netsh

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);
like image 213
Dr developer Avatar asked Nov 21 '25 09:11

Dr developer


2 Answers

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.

like image 145
Mihai Caracostea Avatar answered Nov 22 '25 23:11

Mihai Caracostea


Make user shell execution false

proc.StartInfo.UseShellExecute = false;

and pass true in showWindow parameter

ExecuteApplication("netsh.exe","",cmd, true);
like image 27
Mostafiz Avatar answered Nov 22 '25 23:11

Mostafiz