Running a Command Prompt Script using C# (.Net Windows Forms)

In my recent project that I am currently doing, I came across a problem that requires me automate and run a command prompt script using C# that will initiate multiple apps. Today in this short tutorial, I will show this procedure by opening the Windows paint app and Windows Notepad app, by the click of a button. I will do this using Windows Forms but you can easily replicate in any other .Net environment (for example Unity).

Step by step guide

The first thing I would do is to create a New Sample Project C# WinForm Project.

Create a New Project
Figure: Create a New Project and select Windows Forms App
Name the project
Figure: Name the project as you would like.

The first thing that we need to do is to open the Form1 [Design] Window from the Solution Explorer Window. We need to select the Button Tool from the ToolBox sidepanel on the left and draw a button on the form as shown on the following screenshot. I am keeping things as simple as possible. In the properties window, we just need to change the Button Text to Click Me and the (Name) to runButton. The (Name) portion is important as the portion will serve as a reference to the function that we will write in just a bit. The overall look and fill of the form is shown below:

Form1.cs overview
Figure: Design of the Form with the button “Click Me”

Double clicking the Button “Click Me” will take us to the Form1.cs code window. Visual Studio will create a void method name runButton_Click where we will write our logic that will run when we click the button. The whole Form1.cs code will look like the following:

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace SampleCommandPromptApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void runButton_Click(object sender, EventArgs e)
        {
            try
            {
                string batchFileLocation = @"C:\Users\boltu\Documents\Execute.bat";
                if (File.Exists(batchFileLocation))
                {
                    File.Delete(batchFileLocation);
                }
                StreamWriter file = new StreamWriter(batchFileLocation);
                file.WriteLine("start notepad");
                file.WriteLine("TIMEOUT 10");
                file.WriteLine("start mspaint.exe");
                file.Close();
                Process.Start(batchFileLocation);
            }
            catch (System.Exception err)
            {
                MessageBox.Show("There is an exception: " + err, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

Do not worry, I will explain what happens on each line of code on the void method. We should save the form and run the solution. The expected output would be when you click the button “Click Me” the computer will bring up a command prompt window with notepad getting started at first, followed by 10 seconds interval and finally the paint application will start. If you could manage to get to this far then congratulations.

Project Output
Figure: Project output

Explanation of the code

Our idea was to create a batch formatted text file, with three command prompt lines that needs to be triggered. This file will be created automatically and will be stored in the documents folder.

string batchFileLocation = @"C:\Users\boltu\Documents\Execute.bat";
if (File.Exists(batchFileLocation))
{
    File.Delete(batchFileLocation);
}

The above portion of code will store the location of the filename in a string variable called batchFileLocation for convenience. Additional validation is done to check whether the file exists or not. Out idea is to remove any duplicate file with the same name before we store a new one. File.Delete serves the purpose. In order for these codes to work, we need to bring in System.IO library which we declared at the top.

StreamWriter file = new StreamWriter(batchFileLocation);
file.WriteLine("start notepad");
file.WriteLine("TIMEOUT 10");
file.WriteLine("start mspaint.exe");
file.Close();

The above portion will create a new file onto the desired location and will write down three lines of texts. These lines are actual command prompt commands. You can add as much commands as you like, but the goal here is to trigger the two apps with a 10 seconds interval between each launch. Finally file.Close() allows the created file to finish editing and close the file with all the lines in it.

Process.Start(batchFileLocation);

The above line triggers a command prompt application which will access the batch file and iterate through all the commands and process them one by one. As declared at the beginning of the Form1.cs code, Systems.Diagnostics library will be used to use the above line.

The overall code is put under try catch exception handling since there is possibility of the process failure when processing a file (for example access restriction for saving a file on a particular location). Its always a nice way to keep the code process safe through various ways of exception handling.

Conclusion

This is a short tutorial but it will give an idea of how run a bunch of shell scripts in a command prompt. It also explains how to create a file using .Net and C#, append the file and store the file for future access. Finally it gives a nice overview of the .Net environment itself.