Call Command Prompt For Different Purposes In Different Ways


We have a situation during our GUI application flow, in which we want the command prompt window to execute dynamically. These operations may include executing a script, executing an entire batch file, or even executing a third-party .exe file. In all these scenarios, we need to first call the command prompt. In this article, we are covering five different ways you can call the command prompt for different use cases. Below are those use cases.
  1. Open a command prompt window and auto close it once finished
    This is one of the most common requirements during setup installation. You want to alert the user that some installation is going on by showing a command window but there's no need of any user interaction to close this window. The window will close itself once its operation has finished.

  2. Open a command prompt window, where the user can interact and the user can close
    This is another requirement where opened command prompt window won't close automatically, but user has to close it. If a command window opens like this, the user can interact with it even by adding some inputs. This is a common requirement once you call a .bat file which takes inputs from the user before executing it. So wait for command prompt window to open and wait for user interaction. If you call third party tools like .curl.exe, where it expects multiple input parameters, you need to call the command prompt this way.

  3. Open a command prompt window in hidden mode
    Here, you won't see any running command window, but all operations in this mode are hidden. A perfect example is that you may fetch some information from the background, which user doesn't need to know about or interact with. Such on-demand background operations can be achieved by opening command windows in hidden mode. 

  4. Call a command prompt with multiple commands
    This use case is not related to window mode. If you open a command window either in invisible mode or hidden mode, you will execute multiple commands on it. If you want to run multiple batch processes, then each of the batch calls should able to pass in a single command prompt window call rather than multiple windows.

  5. Open a command prompt with access to its output window
    Here no matter how you open the command window and how you execute it, you are not expecting the default output by the command prompt. You want an elaborate output by accessing the standard output stream of the command prompt. This is helpful in most cases if you want to send some logs during execution errors. You will get each command output in your hand and it's so easy to track the success and failure for a lengthy command prompt operation.

Problem Statement

Any C# developer knows how to call a command prompt dynamically. Below is a straightforward call to the command prompt.
  1. Process p = new Process();  
  2. p.StartInfo.FileName = "cmd.exe";  
  3. p.Start();  
But what about the controls we need before opening the command prompt? What about the above 5 specific scenarios on which we need to open a command prompt? If you refer to forums like stack overflow, you see multiple queries related to "How can I open the command prompt for XXX scenario?" "How can I open a command prompt to do this?" etc...So I thought of five common scenarios.

Sample Project Details

The sample project uploaded has 5 buttons in it, each for different types of command prompt calls. Please see the image below as you would get one like this, once you're running the sample project.
Design Patterns 
Below I explain what each button does:
  1. Auto Close
    A command prompt window will open and then close automatically after command execution. Please verify the output inside output.txt. This is the most common way of calling a command prompt; e.g., executing your bat files and closing the window once finished. You can notice that the code belongs to this button click and the below section is contributing to this auto close behavior. The flag /C is important here.                                                              
    1. StartProcess("/C DIR >> output.txt");

    2. using (Process process = Process.Start(startInfo))  
    3.            {  
    4.                process.WaitForExit();  
    5.                process.Close();  
    6.            }  
  2. Display Window
    A command window will open accepting your input. You need to give the input and then close it by yourself. You need to call the command prompt like this when calling any third-party command prompt tools and they are expecting some inputs during the process; i.e., curl.exe. You can notice the code belongs to this button click and the below section is contributing to this display window behavior. The flag /K is important here.
    1. StartProcess("/K SET /P name=Please enter your name:");  
    2. using (Process process = Process.Start(startInfo))  
    3.             {  
    4.                 process.WaitForExit();  
    5.                 process.Close();  
    6.             }  
  3. No Window
    It's like the first case, but no window would be opened and everything happens from the background. Please verify the output inside output.txt. You can notice the below code belongs to this button click and the below section is contributing to this no window behavior.
    1. ProcessStartInfo processStartInfo = new ProcessStartInfo  
    2.             {  
    3.                 WindowStyle = ProcessWindowStyle.Hidden  
    4.             };  
  4. Multiple Commands
    You call the command prompt but execute more than one command using &&. Please verify the output inside output.txt. You can notice the below code belongs to this button click and the below section has been used to pass multiple dos commands. The takeaway is the && operator.
    1. StartProcess("/C tasklist >> output.txt && dir >> output.txt");  
  5. Custom Output
    You interfere with the output stream of the command prompt and add/remove what the output should be; e.g., if you run a lengthy batch file and try to track any single batch command's fails with its full details, then you need to do this. Here you can inject your own text to the output stream. Please verify the output inside the Visual Studio output window. You can notice the below code belongs to this button click and the below section is contributing to taking control of the command prompt output.
    1. using (var process = Process.Start(processStartInfo))  
    2.            {  
    3.                process.OutputDataReceived += OutputDataReceived;  
    4.                process.ErrorDataReceived += ErrorDataReceived;  
    5.                process.BeginErrorReadLine();  
    6.                process.BeginOutputReadLine();  
    7.                process.WaitForExit();  
    8.                process.Close();  
    9.            }  
    11. private void ErrorDataReceived(object sender, DataReceivedEventArgs e)  
    12.        {  
    13.            Debug.Flush();  
    14.            Debug.WriteLine(string.Format("This is custom information {0}", e.Data));  
    16.        }  
    18.        private void OutputDataReceived(object sender, DataReceivedEventArgs e)  
    19.        {  
    20.            Debug.Flush();  
    21.            Debug.WriteLine(string.Format("This is system information {0}", e.Data));  
    22.        }  
We are registering event handlers for Process.OutputDataReceived and ProcessErrorDataReceived, then calling BeginErrorReadLine() and BeginOutputReadLine(). Inside registered eventhandlers, we are reading the outputs.


Here I covered five specific use cases to call command prompt dynamically and showed how we can make those calls. If you notice any additional use cases, please share here and I will try to add those too. 

Similar Articles