Here is a simple C# code example to help you understand a way to automate the task of running command on CMD. It can be done using System.Diagnostics namespace.
In below example, we are taking an example to run and get result of a simple command “ipconfig” on command prompt. Explanation of code is also given in comment line.
using System;
using System.Diagnostics;
class Program
{
public static void Main()
{
Program obj = new Program();
Obj. CMD_Execute();
}
public void CMD_Execute()
{
try
{
//cmd command which we need to run
string command = "ipconfig";
// '/c' tells cmd that we want it to execute the command that follows, and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
// The following commands are needed to redirect the output of command.
//This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Set to True if you do not create the black window.
procStartInfo.CreateNoWindow = false;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception ex) { Console.WriteLine(ex.Message) ; }
}
}