Execute CMD command from code

142,428

Solution 1

Here's a simple example :

Process.Start("cmd","/C copy c:\\file.txt lpt1");

Solution 2

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.

Solution 3

if you want to start application with cmd use this code:

string YourApplicationPath = "C:\\Program Files\\App\\MyApp.exe"   
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.FileName = "cmd.exe";
processInfo.WorkingDirectory = Path.GetDirectoryName(YourApplicationPath);
processInfo.Arguments = "/c START " + Path.GetFileName(YourApplicationPath);
Process.Start(processInfo);

Solution 4

Using Process.Start:

using System.Diagnostics;

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

Solution 5

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

Share:
142,428
Jake
Author by

Jake

Updated on December 03, 2020

Comments

  • Jake
    Jake over 3 years

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

  • Jake
    Jake almost 15 years
    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?
  • William
    William over 8 years
    I'm trying that, but the second parameter, the argument is not really being passed to the command window, at least not in Windows 8.1
  • M at
    M at almost 8 years
    @William I tested this in windows 10 and it works correctly.
  • M at
    M at about 7 years
    dear @jan'splitek I'm 100% sure about this code . can you open cmd using run ? (your local variables may damaged)
  • amalgamate
    amalgamate over 6 years
    "pro.StartInfo = pro;" should be "pro.StartInfo = proStart;" yes?