[c#] Execute CMD command from code

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

This question is related to c# wpf dll command-line cmd

The answer is


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.


You can use this to work cmd in C#:

ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = @"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();

Don't forget to write /c before your argument !!


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


Argh :D not the fastest

Process.Start("notepad C:\test.txt");

You can do like below:

var command = "Put your command here";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.WorkingDirectory = @"C:\Program Files\IIS\Microsoft Web Deploy V3";
procStartInfo.CreateNoWindow = true; //whether you want to display the command window
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
label1.Text = result.ToString();

Using Process.Start:

using System.Diagnostics;

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

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

Process.Start("cmd");

Here's a simple example :

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

In addition to the answers above, you could use a small extension method:

public static class Extensions
{
   public static void Run(this string fileName, 
                          string workingDir=null, params string[] arguments)
    {
        using (var p = new Process())
        {
            var args = p.StartInfo;
            args.FileName = fileName;
            if (workingDir!=null) args.WorkingDirectory = workingDir;
            if (arguments != null && arguments.Any())
                args.Arguments = string.Join(" ", arguments).Trim();
            else if (fileName.ToLowerInvariant() == "explorer")
                args.Arguments = args.WorkingDirectory;
            p.Start();
        }
    }
}

and use it like so:

// open explorer window with given path
"Explorer".Run(path);   

// open a shell (remanins open)
"cmd".Run(path, "/K");

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);

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to dll

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer PHP 7: Missing VCRUNTIME140.dll How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'? WampServer: php-win.exe The program can't start because MSVCR110.dll is missing msvcr110.dll is missing from computer error while installing PHP installing JDK8 on Windows XP - advapi32.dll error The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there Loading DLLs at runtime in C# Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

Examples related to command-line

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Flutter command not found Angular - ng: command not found how to run python files in windows command prompt? How to run .NET Core console app from the command line Copy Paste in Bash on Ubuntu on Windows How to find which version of TensorFlow is installed in my system? How to install JQ on Mac by command-line? Python not working in the command line of git bash Run function in script from command line (Node JS)

Examples related to cmd

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH VSCode Change Default Terminal How to install pandas from pip on windows cmd? 'ls' in CMD on Windows is not recognized Command to run a .bat file VMware Workstation and Device/Credential Guard are not compatible How do I kill the process currently using a port on localhost in Windows? how to run python files in windows command prompt?