Wednesday, April 30, 2008

How to Execute Command in C# ?

It is normal practice to open the 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. C# programmers have to code in diverse satiations. 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…


In the code given below we create a process i.e. a command process and then invoke 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 references. 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.


using System;


using System.Threading;


 


namespace ExecuteCommand


{


    public class Program


    {


        static void Main(string[] args)


        {


            string command = String.Empty;


 


            // Write to the console.


            Console.Write("Enter the command you wish to execute: ");


 


            // Get the command you wish to execute.


            command = Console.ReadLine().Trim();


 


            // Execute the command synchronously.


            ExecuteCmd exe = new ExecuteCmd();


            exe.ExecuteCommandSync(command);


 


            // Execute the command asynchronously.


            exe.ExecuteCommandAsync(command);


 


            // Your' done !!!


            Console.WriteLine("\nDone !");


            Console.ReadLine();


        }


    }


 


    public class ExecuteCmd


    {


        #region ExecuteCommand Sync and Async


        /// <summary>


        /// Executes a shell command synchronously.


        /// </summary>


        /// <param name="command">string command</param>


        /// <returns>string, as output of the command.</returns>


        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


            }


        }


 


        /// <summary>


        /// Execute the command Asynchronously.


        /// </summary>


        /// <param name="command">string command.</param>


        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


            }


        }


        #endregion


    }


}

10 comments:

emrah said...

Thanks a lot.

..:: PchiwaN ::.. said...

thank you thank you thank you!

i've been for one hour googling for an answer to my questions, and finally found it here!!! then i though i really needed to say thanks

once again, thanks a bunch! :)

Anonymous said...

Hi I love your post - but one thing when I compile (mine is VS 2005) it gave me the error:

No overload for 'ExecuteCommandSync' matches delegate 'System.Threading.ParameterizedThreadStart'

I am successfully used your ExecuteCommandSync function but now need to use the ExecuteCommandAsync function and it doesn't compile...

Thanks.

Sandeep Aparajit said...

Please note that the 'ExecuteCommandAsync' method calls the ExecuteCommandSync method using threads - asynchronously. Hence for using the async method it is important to have the sync method in place. If you use the above code (completely) then you would be able to compile and run it. Please let me know if you still face any issues.

Anonymous said...

Do you have any sample C# service appliction which uses multithreading to initiate the Multiple jobs in the background.(ex shell command)

Grant said...

Thanks Sandeep for taking the time to write this. Is there a way to execute commands without having to start a new cmd.exe process each time? For instance with your code you execute cd .. and it displays the output but it doesn't stick. That was the life of that process. I would like to be able to do
cd ..
dir
something else

and have it all be in the same input output.

I hope I explained myself ok.

Anonymous said...

very helpful and easy to use Sandeep. I've seen another ways to do this but they're not as straightforward as your solution.

Anonymous said...

i want to execute the following command

cd\
cd "C:\Data\Easy"
msiexec /i some.msi /qn

how to execute this command

after execution this command i want to execute another command .....simultaneously..

Sandeep Aparajit said...

You can use '&&' as the command separator. You can specify multiple commands using this operator.
http://www.computerhope.com/cmd.htm

-Sandeep

Dan Pedersen said...

Hi, thanks for this example. Works like a charm.

When i execute the command by using ExecuteCommandAsync(command);, there is no output. Is there a way to get the output out of the asynchronously execution?

Post a Comment