1. Program & Process
A ‘Program’ is an executable stored in the physical disc. Say for example Notepad.Exe stored in windows System32 folder is called as a ‘Notepad Program’. When the program in secondary storage (Disc) loads into primary memory for executing machine code in it, we call it as a ‘Process’. Windows has the power of spawning multiple tasks at a time and we call windows as a Multi-Tasking operating system for that reason. When all these running in the background, they fight for the shared resources. OK, in this article we will see how to spawn a process from a C# application.
2. About This C# Process Example
The below screenshot shows the application example:
The sample application has two parts. The first part starts a notepad process when you click the ‘Start’ (Marked as 1) button. You can enter the text document location in the text box (Marked as 2) before clicking the start button. When a text document is specified, the notepad process opens that document.
In the second part, the example app runs the batch as a process when we click the start button (Marked as 7). The batch file performs a ‘DOS Copy’ operation, which requires Source and Destination locations. We can supply these data can through two text boxes (Marked as 3 & 4). When a batch file execution continues, we can see a console window in the background. The checkbox ‘Make Silent’ (marked as 5) suppresses the background command window. The checkbox ‘Notify when closed’ (Marked as 6) when checked, allows the application receiving the notification when process finished its operation. In our case, when the batch file completes the copy action, our example gets a notification.
3. Starting the ‘Notepad.Exe’ Process
3.1 Using Namespace
To create a process, we need to use Process class, which can be found in the ‘
System.Diagnostics
’ namespace. Below is the using statement for it:
1 2 |
//Sample 01: Use Diagnostics namespace using System.Diagnostics; |
3.2 Starting Notepad
The
Start()
Method of the
Process
Class will spawn a process. In our case, we supply the document name to the start method when the user gives path in the Document Path text box. Note, we do not do path validation in the code. So, when you are testing, provide a valid text in the document path text field. Below is the code which open Notepad as a process:
1 2 3 4 5 6 7 8 |
//Sample 03: Start Notepad process. private void btnStartNotepad_Click(object sender, EventArgs e) { if (txtDocPath.Text == String.Empty) Process.Start("Notepad.exe"); else Process.Start("Notepad.exe", txtDocPath.Text); } |
4. Batch File With Parameters
In this example, our application starts the ‘copy.bat’ batch file as a Process. The copy.bat file’s is shown below:
The batch file copies one or more files or directories from the source location to the destination location. We can pass source and destination locations as parameters to the batch file and these will be substituted to %1 and %2 in the batch file. Our C# example application passes these parameters as arguments to the Batch File, and we will see that in the next session.
5. Starting ‘Copy.Bat’ as Process
In this section, we will run the ‘copy.bat’ as a process from our sample windows form. Here, we will also learn how to pass parameters to the batch file from C# code.
5.1 Private Member
First, we declare the
Process
reference as a private data member of the class. The code is below:
1 2 |
//Sample 02: Process for the batch private Process BatchProc = null; |
5.2 Source and Destination Paths
When source and destination path text boxes are empty, we will not start the copy task and return from the ‘Start’ button click event handler. Note, validation for the proper path is not done and hence while executing the sample application, we must enter a valid path into the text boxes. The code is below:
1 2 3 4 5 |
//4.1: Return when the strings are empty. However, path validation //not done if (txtSrcPath.Text == string.Empty || txtDestPath.Text == string.Empty) return; |
5.3 Passing Process Argument Via ProcessStartInfo
The
ProcessStartInfo
Class is useful to set information needed to start the process. In our example, we created
ProcInfo
object of type
ProcessStartInfo
and stated the Copy.bat batch file name through its
FileName
property. Since we do not tell the path name, the ‘Copy.bat’ batch file should live in the same folder where our C# example executable exists. Next, we fill the
ProcInfo
object with the arguments for the copy operation. Means, we fill the source and target file location through its property,
Arguments
.
1 2 3 4 5 |
//4.2: Populate Process Information ProcessStartInfo ProcInfo = new ProcessStartInfo(); ProcInfo.FileName = "Copy.bat"; ProcInfo.Arguments = "\"" + txtSrcPath.Text + "\" " + "\"" + txtDestPath.Text + "\""; |
While forming the Argument we use the escape sequence \” to carry the double quote as the path may have spaces. Parameter 1 and parameter 2 for the batch file are split by a space while making the string for the
Argument
member of the
ProcessStartInfo
class. The below picture shows how the string concatenation is applied:
The batch file requires the yellow highlighted double quotes as some path may contain spaces. In the above picture D:\Temp does not have any space but the path in argument 1 is having the space. As we take the inputs from the UI, it is advisable to use the escape sequence while forming Argument string. Hence we separate Parameter 1 and Parameter 2 by a blank space.
5.4 Starting File Copy
Once
ProcessStartInfo
structure is ready, we can pass that structure to the
Start()
method. This is shown below:
1 2 |
//4.4: Start the Process and Hook-up process Exit Event BatchProc = Process.Start(ProcInfo); |
At this stage, the our sample will spawn the DOS Console Window and executes the Copy.bat. The net effect is the batch file performing the copy based on the parameter present in the text boxes for source and target paths.
6. Starting Process Silent
Sometimes we need to start a batch file in silent mode. Means, the application responsible for starting the process should not show any background window and the task should go silent. Setting the
WindowStyle
property of the
ProcessStartInfo
to the
ProcessWindowStyle.Hidden
constant can do this. The code for silently starting the process is below:
1 2 3 4 5 |
//4.3: Start the process in silent Mode3 if (chkBoxSilent.Checked == true) { ProcInfo.WindowStyle = ProcessWindowStyle.Hidden; } |
7. Process Completion Notification
Sometimes, we need to notify the parent application which started the process by stating that the task is completed or exited. In our case, the batch file exits after copying the file from source to destination. The application starting the process can handle the
Exited
Event of the Process class to get notified when it quits. The code is below:
1 2 3 4 5 |
if (chkWhenClosed.Checked == true) { BatchProc.EnableRaisingEvents = true; BatchProc.Exited += new System.EventHandler(Batch_Done); } |
The handler for the above exited event is shown below which displays a message box stating copy operation is completed:
1 2 3 4 5 6 |
//Sample 05: Handle Batch completed event private void Batch_Done(object sender, EventArgs e) { MessageBox.Show("Copy Completed!"); BatchProc.Exited -= new System.EventHandler(Batch_Done); } |
Video: Shows how our C# Spawn Process Example Works
Source Code: Download C# Spawn Process Example From Google Drive
Categories: C#
Tags: Exited Event, ProcessStartInfo, ProcessStartInfo.Arguments, ProcessStartInfo.FileName, ProcessWindowStyle.Hidden, Start(), System.Diagnostics