views:

886

answers:

6

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

+1  A: 

Are you asking how to bring up a command windows? If so, you can use the Process object ...

Process.Start("cmd");
JP Alioto
+4  A: 

Using Process.Start:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process.Start("example.txt");
    }
}
Mitch Wheat
A: 

Argh :D not the fastest

Process.Start("notepad C:\test.txt");
Acron
+5  A: 

Here's a simple example :

Process.Start("cmd","/C copy c:\\file.txt lpt1");
Andreas Grech
nice and simple. Elegant!
Preet Sangha
+1  A: 

How about you creat a batch file with the command you want, and call it with Process.Start

dir.bat content:

dir

then call:

Process.Start("dir.bat");

Will call the bat file and execute the dir

Carlo
Great idea! I did the Process.Start("test.bat") but an error pops up saying "An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll". Any ideas?
Jake
Oh nvm, fixed it. Thanks a lot Carlo. Really good idea, helped a lot.
Jake
No problem, glad I could help! Don't forget to mark this as the correct answer.
Carlo
+1  A: 

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.

Ashley Davis