Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute CMD command from code

In C# WPF: I want to execute a CMD command, how exactly can I execute a cmd command programmatically?

like image 897
Jake Avatar asked Aug 10 '09 16:08

Jake


People also ask

Can Python run CMD commands?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do I run a command prompt in C++?

You can execute Windows Command prompt commands using a C++ function called system(); . For safer standards you are recommended to use Windows specific API'S like ShellExecute or ShellExecuteEx. Here is how to run CMD command using system() function.


2 Answers

Here's a simple example :

Process.Start("cmd","/C copy c:\\file.txt lpt1"); 
like image 142
Andreas Grech Avatar answered Sep 22 '22 06:09

Andreas Grech


As mentioned by the other answers you can use:

  Process.Start("notepad somefile.txt"); 

However, there is another way.

You can instance a Process object and call the Start instance method:

  Process process = new Process();   process.StartInfo.FileName = "notepad.exe";   process.StartInfo.WorkingDirectory = "c:\temp";   process.StartInfo.Arguments = "somefile.txt";   process.Start(); 

Doing it this way allows you to configure more options before starting the process. The Process object also allows you to retrieve information about the process whilst it is executing and it will give you a notification (via the Exited event) when the process has finished.

Addition: Don't forget to set 'process.EnableRaisingEvents' to 'true' if you want to hook the 'Exited' event.

like image 42
Ashley Davis Avatar answered Sep 23 '22 06:09

Ashley Davis