Click here to Skip to main content
Click here to Skip to main content
Go to top

Run console application from a .NET application

, 30 May 2010
Rate this:
Please Sign up or sign in to vote.
To execute command line (console applications) in the shell or via command prompt (cmd) from a .NET application can be done easily. But when it should be more than fire and forget, it becomes more complicated.

The base class library of the .NET Framework doesn't provide a mechanism to execute a console application or something in the command prompt out of the box. The execution of a tool which only has textual output isn't a challenge at all, but if want to interact with it (read the output and react on it), it becomes more complicated.

Technical Basics

With the Process class, you can start any application. The ProcessStartInfo gives you the ability to configure it more deeply. UseShellExecute of the ProcessStartInfo class must be set to false if you want to redirect the standard input, output and errors. So internally it uses the operating system shell to start the process. When the properties RedirectStandardInput, RedirectStandardOutput and RedirectStandardError are set to true, you can use the Process class to get a initialized StreamWriter from the StandardInput property and a initialized StreamReader from the StandardOutput and the StandardError property. The writer and readers allow you to interact with the console application. The CreateNoWindow defines that no window should be created for the called application. When you run your application and UseShellExecute is set to true, also no window will be created.

Command Prompt

The command prompt or cmd is a command line interpreter which allows you to execute and interact with applications that have a textual user interface or no interface (only arguments which are passed in at startup).

public static string RunCmd(params string[] commands)
{
    string returnvalue = string.Empty;

    ProcessStartInfo info = new ProcessStartInfo("cmd");
    info.UseShellExecute = false; 
    info.RedirectStandardInput = true;
    info.RedirectStandardOutput = true;
    info.CreateNoWindow = true;

    using (Process process = Process.Start(info))
    {
        StreamWriter sw = process.StandardInput;
        StreamReader sr = process.StandardOutput;

        foreach (string command in commands)
        {
            sw.WriteLine(command);
        }

        sw.Close();
        returnvalue = sr.ReadToEnd();
    }

    return returnvalue;
}

When you call RunCmd(...), you can pass in multiple commands and you will receive the result which is normally shown in the command prompt. You can't interact with the command prompt multiple times in the same process, like write command, receive result, write command and so on. The StreamWriter must be closed, without that, the StreamReader will not return any result. If you have to react to the output of a command, you have to call the method multiple times with your commands. The following sample calls nslookup two times, the return value is also shown below.

RunCmd("nslookup www.google.com", "nslookup www.microsoft.com");
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\Sample\bin\Debug>nslookup www.google.com
Server:  xxx.sample.com
Address:  200.001.001.161

Name:    www.l.google.com
Addresses:  74.125.43.99
	  74.125.43.103
	  74.125.43.104
	  74.125.43.105
	  74.125.43.106
	  74.125.43.147
Aliases:  www.google.com


C:\Sample\bin\Debug>nslookup www.microsoft.com
Server:  xxx.sample.com
Address:  200.001.001.161

Name:    lb1.www.ms.akadns.net
Addresses:  64.4.31.252
	  207.46.19.190
	  207.46.19.254
Aliases:  www.microsoft.com
	  toggle.www.ms.akadns.net
	  g.www.ms.akadns.net 

Console Applications

You can also execute console applications without using command prompt. It allows you to get only the return message from the application without the crap you receive from the command prompt. The sample shows a implementation for console applications which only has startup parameters.

public static string Run(string fileName, string args)
{
    string returnvalue = string.Empty;

    ProcessStartInfo info = new ProcessStartInfo(fileName);
    info.UseShellExecute = false; 
    info.Arguments = args;
    info.RedirectStandardInput = true;
    info.RedirectStandardOutput = true;
    info.CreateNoWindow = true;

    using (Process process = Process.Start(info))
    {
        StreamReader sr = process.StandardOutput;
        returnvalue = sr.ReadToEnd();
    }

    return returnvalue; 
}

License

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

Share

About the Author

Mattia Baldinger
Software Developer
Switzerland Switzerland
No Biography provided
Follow on   Twitter

Comments and Discussions

 
QuestionPassing Arguments to .exe file generated by c++ program PinmemberHussain ahmad26-Aug-14 9:40 
Questionregarding console application in c#.net Pinmemberpunk12322-Jan-13 0:50 
QuestionHow can run a command on Visual studio command prompt from windows application Pinmemberranjitcherian28-Nov-11 7:49 
QuestionA different solution PinmemberKeith Tyra24-Aug-11 10:09 
QuestionHow to interact with command prompt PinmemberDoug Femec8-Aug-10 6:32 
GeneralStream redirecting PinmemberMiguel Castillo8-Jun-10 3:39 
GeneralUseShellExecute must be set to False (artical error) Pinmemberbobthetomato17627-May-10 8:44 
GeneralRe: UseShellExecute must be set to False (artical error) PinmemberMattia Baldinger30-May-10 19:35 
GeneralNice! PinmemberPlebs24-May-10 14:44 
GeneralArticle is Ok! Pinmembervenomation9-May-10 8:42 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140922.1 | Last Updated 31 May 2010
Article Copyright 2010 by Mattia Baldinger
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid