Home > other >  Run windows command without cmd.exe from C#
Run windows command without cmd.exe from C#

Time:11-24

I am attempting to run a windows command (e.g. whoami) without calling cmd.exe (or powershell) directly using C#.

Within VB this is possible using CreateObject(WScript.Shell) it obviously does not have to be the same method as within the VB, although that would be nice, but I just do not want to call cmd.exe directly.

How would I be able to achieve this?

CodePudding user response:

This runs a console program, waits for exit and reads the output. I changed the cmd to ping since that takes longer and I can verify no console window opens.

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "ping.exe";
startInfo.Arguments = "google.com";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
// This wasn't needed
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;

Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
    processTemp.Start();
    textBox1.Text = processTemp.StandardOutput.ReadToEnd();
    processTemp.WaitForExit();
}
catch (Exception ex)
{
    textBox1.Text = ex.Message;
}

CodePudding user response:

You could call whoami.exe and capture the output directly. The key is UseShellExecute = false to run the executable directly.

var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = @$"{Environment.ExpandEnvironmentVariables("%systemroot%")}\system32\whoami.exe",
        Arguments = // Put any command line arguments here
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

proc.Start();
string line = proc.StandardOutput.ReadToEnd();
  •  Tags:  
  • c#
  • Related