Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / Visual Basic

Run console application from a .NET application

Rate me:
Please Sign up or sign in to vote.
4.13/5 (30 votes)
30 May 2010CPOL2 min read 124.3K   70   10
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).

C#
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.

C#
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.

C#
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)



Comments and Discussions

 
Questionnot able to download code from CommandLine sample solution (24.42 KB) Pin
Member 1320780525-Jul-17 6:42
Member 1320780525-Jul-17 6:42 
QuestionPassing Arguments to .exe file generated by c++ program Pin
Hussain ahmad26-Aug-14 9:40
Hussain ahmad26-Aug-14 9:40 
Questionregarding console application in c#.net Pin
punk12322-Jan-13 0:50
punk12322-Jan-13 0:50 
QuestionHow can run a command on Visual studio command prompt from windows application Pin
ranjitcherian28-Nov-11 7:49
ranjitcherian28-Nov-11 7:49 
QuestionA different solution Pin
Keith Tyra24-Aug-11 10:09
Keith Tyra24-Aug-11 10:09 
QuestionHow to interact with command prompt Pin
Doug Femec8-Aug-10 6:32
Doug Femec8-Aug-10 6:32 
GeneralStream redirecting Pin
Miguel Castillo8-Jun-10 3:39
Miguel Castillo8-Jun-10 3:39 
GeneralUseShellExecute must be set to False (artical error) Pin
bobthetomato17627-May-10 8:44
bobthetomato17627-May-10 8:44 
GeneralRe: UseShellExecute must be set to False (artical error) Pin
User 661920730-May-10 19:35
User 661920730-May-10 19:35 
GeneralArticle is Ok! PinPopular
venomation9-May-10 8:42
venomation9-May-10 8:42 

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.