Click here to Skip to main content
14,870,291 members
Articles / Programming Languages / C#
Posted 11 May 2008

Tagged as


92 bookmarked

How to Execute a Command in C# ?

Rate me:
Please Sign up or sign in to vote.
4.39/5 (68 votes)
11 May 2008CPOL2 min read
This article will help you to execute a command in C#, just like we execute a command using the Windows command prompt


It is normal practice to open the Windows command prompt and execute commands. The command when executed shows the result onto the screen. There are many commands that we execute daily such as dir, find, etc. A situation may arise when you want to execute a (shell) command from the C# application.

Don't worry!!! Here is the code to do so…

Using the Code

The code given below creates a process i.e. a command process and then invokes the command that we want to execute. The result of the command is stored in a string variable, which can then be used for further reference. The command execution can happen in two ways, synchronously and asynchronously. In the asynchronous command execution, we just invoke the command execution using a thread that runs independently. The code has enough comments, hence making it self-explanatory.

Below is the code to execute the command synchronously:

/// <span class="code-SummaryComment"><summary></span>
/// Executes a shell command synchronously.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="command">string command</param></span>
/// <span class="code-SummaryComment"><returns>string, as output of the command.</returns></span>
public void ExecuteCommandSync(object command)
         // create the ProcessStartInfo using "cmd" as the program to be run,
         // and "/c " as the parameters.
         // Incidentally, /c tells cmd that we want it to execute the command that follows,
         // and then exit.
    System.Diagnostics.ProcessStartInfo procStartInfo =
        new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

    // The following commands are needed to redirect the standard output.
    // This means that it will be redirected to the Process.StandardOutput StreamReader.
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    // Do not create the black window.
    procStartInfo.CreateNoWindow = true;
    // Now we create a process, assign its ProcessStartInfo and start it
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procStartInfo;
    // Get the output into a string
    string result = proc.StandardOutput.ReadToEnd();
    // Display the command output.
      catch (Exception objException)
      // Log the exception

The above code invokes the cmd process specifying the command to be executed. The option procStartInfo.RedirectStandardOutput is set to true, since we want the output to be redirected to the StreamReader. The procStartInfo.CreateNoWindow property is set to true, as we don't want the standard black window to appear. This will execute the command silently.

Below is the code to execute the command asynchronously:

/// <span class="code-SummaryComment"><summary></span>
/// Execute the command Asynchronously.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="command">string command.</param></span>
public void ExecuteCommandAsync(string command)
    //Asynchronously start the Thread to process the Execute command request.
    Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
    //Make the thread as background thread.
    objThread.IsBackground = true;
    //Set the Priority of the thread.
    objThread.Priority = ThreadPriority.AboveNormal;
    //Start the thread.
   catch (ThreadStartException objException)
    // Log the exception
   catch (ThreadAbortException objException)
    // Log the exception
   catch (Exception objException)
    // Log the exception

If we observe carefully, the asynchronous execution of the command actually invokes the synchronous command execution method using a thread. The thread runs in the background making the command execution asynchronous in nature.

In the above execution sample, we find that there are two result sets of the command "dir". The first one appears immediately after the command and the second appears after the "Done!" statement. In this case, the first one is the synchronous execution of the command, which happens immediately and the second is the asynchronous execution of the "dir" command.

Points of Interest

I always thought of having some code that will execute my DOS commands, finally I had to build it.

You can find some more interesting stuff here.


  • 12th May, 2008: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sandeep Aparajit
Software Developer (Senior)
United States United States
Sandeep has 9+ yrs of IT experience. He is Microsoft Certified Technology Specialist and has been certified for Analyzing Requirements and Defining Microsoft .NET Solution Architectures.
He is an active member of:
1. MSDN Forums

My Blog
More Info

Comments and Discussions

QuestionThis article is being copied without permission Pin
Raj00630-Jul-19 19:04
MemberRaj00630-Jul-19 19:04 
Questionhow to execute dotnet test command in this program? Pin
Member 1389141828-Jun-18 10:56
MemberMember 1389141828-Jun-18 10:56 
QuestionPDF not generated Pin
Keepr13-Dec-16 0:14
MemberKeepr13-Dec-16 0:14 
GeneralMy vote of 5 Pin
hasiabewardana3-Apr-16 21:06
Memberhasiabewardana3-Apr-16 21:06 
BugWorks, but not with commands that need additional input Pin
Member 1206637117-Oct-15 7:19
MemberMember 1206637117-Oct-15 7:19 
GeneralMy vote of 5 Pin
Member 1178934324-Jun-15 3:56
MemberMember 1178934324-Jun-15 3:56 
Questionproject not opening Pin
Divsheen29-Apr-15 0:32
MemberDivsheen29-Apr-15 0:32 
Questionhow to execute command lines from C# Pin
Member 1139937124-Jan-15 4:21
MemberMember 1139937124-Jan-15 4:21 
AnswerRe: how to execute command lines from C# Pin
PIEBALDconsult24-Jan-15 4:25
professionalPIEBALDconsult24-Jan-15 4:25 
GeneralRe: how to execute command lines from C# Pin
Member 1139937124-Jan-15 7:01
MemberMember 1139937124-Jan-15 7:01 
QuestionCannot read configuration file due to insufficient permissions. Pin
hernaldo.gonzalez28-May-14 10:52
Memberhernaldo.gonzalez28-May-14 10:52 
AnswerRe: Cannot read configuration file due to insufficient permissions. Pin
Sandeep Aparajit29-Aug-14 12:23
MemberSandeep Aparajit29-Aug-14 12:23 
GeneralRe: Cannot read configuration file due to insufficient permissions. Pin
Member 110683632-Dec-14 20:49
MemberMember 110683632-Dec-14 20:49 
QuestionI have problem needs your help Pin
osamaworx23-Jan-14 3:21
Memberosamaworx23-Jan-14 3:21 
GeneralMy vote of 5 Pin
Gun Gun Febrianza29-May-13 6:55
Member Gun Gun Febrianza29-May-13 6:55 
QuestionNot working :-( Pin
Amogh Natu21-May-13 23:19
professionalAmogh Natu21-May-13 23:19 
GeneralMy vote of 5 Pin
Member 83129214-Oct-12 2:06
MemberMember 83129214-Oct-12 2:06 
Question:) Pin
naymyohaen2-Jul-12 21:45
Membernaymyohaen2-Jul-12 21:45 
GeneralMy vote of 5 Pin
Carlos ABS11-Apr-12 2:54
MemberCarlos ABS11-Apr-12 2:54 
GeneralMy vote of 5 Pin
Milton Rodríguez22-Nov-11 2:46
MemberMilton Rodríguez22-Nov-11 2:46 
QuestionWhat if i want a continues commands?? Pin
RIKISH1-Nov-11 23:34
MemberRIKISH1-Nov-11 23:34 
Questionre:How to Execute a Command in C# ? Pin
hafizhanif31-Oct-11 20:26
Memberhafizhanif31-Oct-11 20:26 
GeneralMy vote of 5 Pin
IanJ196525-May-11 20:39
MemberIanJ196525-May-11 20:39 
GeneralMy vote of 1 Pin
Member 775354214-Mar-11 9:11
MemberMember 775354214-Mar-11 9:11 
GeneralMy vote of 5 Pin
bbakkebo2-Mar-11 3:56
Memberbbakkebo2-Mar-11 3:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.