Click here to Skip to main content
Click here to Skip to main content

How to Execute a Command in C# ?

By , 11 May 2008
 

Introduction

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)
{
     try
     {
         // 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;
    proc.Start();
    // Get the output into a string
    string result = proc.StandardOutput.ReadToEnd();
    // Display the command output.
    Console.WriteLine(result);
      }
      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)
{
   try
   {
    //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.
    objThread.Start(command);
   }
   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.

History

  • 12th May, 2008: Initial post

License

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
United States United States
Sandeep has 7+ 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
2. CodeProject.com
3. Community-Credit.com
4. Blogspot.com
 
You can find his contributions at:
My Blog
Photography

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5member Gun Gun Febrianza29-May-13 6:55 
this is waht i need . thank you so much Smile | :)
QuestionNot working :-(professionalAmogh Natu21-May-13 23:19 
I used the same code. But it doesn't seem to work. I have given everything correctly but still the service is not starting or stopping.
Thanks,
Amogh Natu.

GeneralMy vote of 5memberMember 83129214-Oct-12 2:06 
Works great.
Question:)membernaymyohaen2-Jul-12 21:45 
Thanks
GeneralMy vote of 5memberCarlos ABS11-Apr-12 2:54 
Very simple, and works!
GeneralMy vote of 5memberMilton Rodríguez22-Nov-11 2:46 
That's what I was looking for! Tks for that! Hope this work also :P
QuestionWhat if i want a continues commands??memberRIKISH1-Nov-11 23:34 
Hi,
 
thanks for this prog, it is so clear and useful,what if i want to run some command, but not a single one?
some continues commands?
ex. I need to connect to some ftp server, and enter some user name and password..then some commands..etc..
how can I do it? should I add info to procStartInfo param?
 
TIA
Rika.
Questionre:How to Execute a Command in C# ?memberhafizhanif31-Oct-11 20:26 
i use this code this work fine in console application and also show/return the result of command, but when i use this code into simple form base application and send command from text box. command works fine but "string result = proc.StandardOutput.ReadToEnd();" always return null.
 
So is there any command or function which can show the status of DOS base command and result of that
The World is very beautiful. Seearch its creature and what is the purpose of our creation.

GeneralMy vote of 5memberIanJ196525-May-11 20:39 
Thanks for this, will be using it in a Mediaportal plugin very soon.
GeneralMy vote of 1memberMember 775354214-Mar-11 9:11 
Process.Start() does NOT run commands synchronously. Your "sync code run" runs the command asynchronously!
GeneralMy vote of 5memberbbakkebo2-Mar-11 3:56 
Simple to follow and just plain works. Thanks
GeneralMy vote of 5membercnndnmdfn31-Oct-10 22:28 
It execute successfully.
GeneralNeed to run asynchronously and capture outputmemberbrudog569-Jul-10 5:00 
Hi Sandeep,
 
This is very helpful, however, I need to run a shell command asynchronously AND have the output from the command returned as a string (not just printed to the console). Do you have any ideas?
 
Thanks,
Mike
GeneralMy vote of 2memberPriyank Bolia16-Mar-09 23:27 
nothing great about this trick, should have used some Asynchronous callback methods, etc. to notify the command results back to the main thread.
Generalftp command linemembermega1510-Jun-08 11:53 
Hi, i saw your example, its really interesting, but i dont know how to do it for a command like "ftp" witch need's to pass for example the user and the password to interact after the command ftp was make.
 
Thank you
GeneralRe: ftp command linememberneal12321-Jan-10 19:09 
Hi,
 
I know your thread is old but I just gont thru your post and also found some nearest solution for you... You might seen this then ignore my this post or please visit below link.
 
Asynchronous Method Invocation[^]
 
Regards,
 
Neal.

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 12 May 2008
Article Copyright 2008 by Sandeep Aparajit
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid