Sometimes, when working with a C# project, we may want to run CMD Command using C# and show its output or get output, so in this article, I have mentioned how to Execute Command Prompt(CMD) commands from C# with a console application example.
So here is the simple console application program where we will execute CMD command "ipconfig" using C#.
using System;
using System.Diagnostics;
namespace CMDCommandUsingCsharp
{
public class Program
{
static void Main(string[] args)
{
var proc1 = new ProcessStartInfo();
//cmd command
var 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);
// The following commands are needed to redirect the standard output.
//This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// 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);
}
}
}
I have explained some important parts of the code using Comments.
Output:
Ethernet adapter Ethernet:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Wireless LAN adapter Local Area Connection* 1:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Wireless LAN adapter Local Area Connection* 10:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Wireless LAN adapter Wi-Fi:
Connection-specific DNS Suffix . :
IPv6 Address. . . . . . . . . . . : xxxx:xxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx::xxxx:xx:xxxx:17ea%7
IPv4 Address. . . . . . . . . . . : XXX.XXX.XX.XXX
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : xxxx::xxxx:xxxx:xxxx:8b5%7
XXX.XXX.XX.1
In the above code,
UseShellExecute
Gets or sets a value indicating whether to use the operating system shell to start the process.RedirectStandardOutput
redirects the standard outputCreateNoWindow true
if the process should be started without creating a new window to contain it, otherwise, false.
In the above code, you can also pass parameters with Commands while executing CMD Commands.
You may also like to read:
Multiple Fields Order By With Linq
Resize image in C# (Console application example)Sort Dictionary by Value in C#
Get enum key by value in Typescript
Split String into Array in Powershell