xxxxxxxxxx
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
// Create a new process instance
Process process = new Process();
// Set the start info for the process
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c echo Hello World"; // Replace with desired command
// Set the process to run hidden (optional)
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// Start the process
process.Start();
// Wait for the process to exit
process.WaitForExit();
// Display the process exit code
Console.WriteLine($"Process Exit Code: {process.ExitCode}");
Console.ReadLine();
}
}
xxxxxxxxxx
using System.Diagnostics;
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/c ipconfig",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Console.WriteLine(output);
The RedirectStandardOutput property is set to true to capture the output of the command. The UseShellExecute property is set to false to run the command in a new console window. The CreateNoWindow property is set to true to prevent the console window from being displayed.
The Start method is called to start the process. The StandardOutput property is read to capture the output of the command. The WaitForExit method is called to wait for the command to complete. The output of the command is printed to the console.
By using the Process class in C#, you can run CMD commands and capture their output in your application. This approach can be useful when you need to automate tasks that require command line tools or utilities.
xxxxxxxxxx
string strCmdText = "pip install -r requirements.txt";
Process.Start("CMD.exe", strCmdText);