5,427,303 members and growing! (14,952 online)
Email Password   helpLost your password?
Languages » C# » How To     Intermediate License: The Code Project Open License (CPOL)

How to Execute a Command in C# ?

By Sandeep Aparajit

This article will help you to execute a command in C#, just like we execute a command using the Windows command prompt
C# (C# 1.0, C# 2.0, C# 3.0, C#), Dev

Posted: 12 May 2008
Updated: 12 May 2008
Views: 4,632
Bookmarked: 9 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
14 votes for this Article.
Popularity: 2.77 Rating: 2.42 out of 5
6 votes, 42.9%
1
3 votes, 21.4%
2
1 vote, 7.1%
3
0 votes, 0.0%
4
4 votes, 28.6%
5

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:

/// <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
      }
}

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:

/// <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
   }
}

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


Sandeep is a senior software developer at TCS, Pune. He has 4+ 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:
http://sandeep-aparajit.blogspot.com

Occupation: Software Developer (Senior)
Company: Tata Consultancy Services
Location: India India

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 1 of 1 (Total in Forum: 1) (Refresh)FirstPrevNext
Subject  Author Date 
Generalftp command linemembermega1512:53 10 Jun '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 May 2008
Editor: Deeksha Shenoy
Copyright 2008 by Sandeep Aparajit
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project