Click here to Skip to main content
11,635,123 members (77,868 online)
Click here to Skip to main content

Run console application from a .NET application

, 30 May 2010 CPOL 74.7K 67
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

You may also be interested in...

Comments and Discussions

 
QuestionPassing Arguments to .exe file generated by c++ program Pin
Hussain ahmad26-Aug-14 9:40
memberHussain ahmad26-Aug-14 9:40 
Questionregarding console application in c#.net Pin
punk12322-Jan-13 0:50
memberpunk12322-Jan-13 0:50 
QuestionHow can run a command on Visual studio command prompt from windows application Pin
ranjitcherian28-Nov-11 7:49
memberranjitcherian28-Nov-11 7:49 
QuestionA different solution Pin
Keith Tyra24-Aug-11 10:09
memberKeith Tyra24-Aug-11 10:09 
I was trying to trigger a console application from a VB.NET web application, but even this way I couldn't get it to work. My situation was that the console app would run perfectly fine when started manually, but wouldn't run at all when called from the web app. I went through folder and file permissions, IIS permissions/user emulation, and even .NET framework security settings - nothing worked.

I created a system scheduled task that would activate the console app, set it to disabled so that it normally wouldn't run, and set its permissions so that anyone could trigger it. Then I changed my web app to make a system call:

Process.Start("C:\Windows\system32\schtasks.exe", "/run /tn Print")

where Print is the name I gave the scheduled task. This still didn't work in the live version and I found that I had to go into IIS to the application pool to which the web site was attached and change its properties. On the Identity tab I chose "configurable" and entered a user with system permissions; then everything worked.

Security-wise this might not be the best approach, but it worked and the apps in question are limited-function tools running on an intranet.
QuestionHow to interact with command prompt Pin
Doug Femec8-Aug-10 6:32
memberDoug Femec8-Aug-10 6:32 
GeneralStream redirecting Pin
Miguel Castillo8-Jun-10 3:39
memberMiguel Castillo8-Jun-10 3:39 
GeneralUseShellExecute must be set to False (artical error) Pin
bobthetomato17627-May-10 8:44
memberbobthetomato17627-May-10 8:44 
GeneralRe: UseShellExecute must be set to False (artical error) Pin
Mattia Baldinger30-May-10 19:35
memberMattia Baldinger30-May-10 19:35 
GeneralNice! Pin
Plebs24-May-10 14:44
memberPlebs24-May-10 14:44 
GeneralArticle is Ok! Pin
venomation9-May-10 8:42
membervenomation9-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 | Terms of Use | Mobile
Web04 | 2.8.150728.1 | Last Updated 31 May 2010
Article Copyright 2010 by Mattia Baldinger
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid