Wednesday, 6 May 2015

Starting a Process in C# .NET .bat file



Download Files:
 
Introduction

A program is an executable stored in a physical disc. Say for example Notepad.exe stored in the Windows System32 folder is called the Notepad program. When the program in secondary storage (Disc) loads into primary storage for the execution of instructions set in it, we call it a process. Windows has the capability of spawning multiple processes at a time and we call Windows a multi-tasking operating system. When all processes running in the background they compete for the shared resources. OK, this article we will see how to spawn a process from a C# application.

About the Example

The following screen shot shows the application example:



The sample application has two parts. The first part starts a Notepad process when the “Start” (marked as 1) button is clicked. You can enter the text document location in the TextBox (marked as 2) before clicking the start button. When a text document is specified, the notepad process opens that document. In the second part, a batch file is began as the process by clicking the start button (marked as 7). The batch file actually does a xcopy command that requires source and destination locations. The data can be supplied using two text boxes (marked as 3 and 4). When a batch file execution continues you 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 the process finished its operation.

Starting the Notepad Process
To create a process, we need to use the Process class that can be found in the System.Diagnostics namespace. The following is the using statement for it.
  1. //Sample 01: Use Diagnostics namespace   
  2. using System.Diagnostics;   
The Start method of the Process class spawns a process. In our case, we supply the document name to the Process start method when the path is given in the Document Path text box. Note that path validation is not done in the code, so when you are testing, provide a valid text document path.
  1. //Sample 03: Start Notepad process.   
  2. private void btnStartNotepad_Click(object sender, EventArgs e)   
  3. {  
  4.     if (txtDocPath.Text == String.Empty) Process.Start("Notepad.exe");  
  5.     else Process.Start("Notepad.exe", txtDocPath.Text);  
  6. }  
About the Batch File


This demo application starts the “copy.bat” batch file as a Process. The content of the copy.bat is shown below.



The batch file actually copies one or more files or directories from the specified source to the specified destination. The source and destination locations can be passed as parameters to the batch file and these parameters will be substituted from the %1 and %2 in the batch file. Our C# example application passes these parameters as arguments to the Process and we will see that in the next session.

Running a batch file as a process

The code explanation below describes how a batch file can be run as a process.

First, the process is declared as a private data member of the class. The code is given below.
  1. //Sample 02: Process for the batch   
  2. private Process BatchProc = null;   
When the source and destination path text boxes are empty we will not start the process and return from the “Start” button click event procedure. Note that validation for the proper path is not done and hence when executing the sample application, a valid path should be entered into the text boxes. The code is given below.
  1. //4.1: Return when the strings are empty. However, path validation not done   
  2. if (txtSrcPath.Text == string.Empty || txtDestPath.Text == string.Empty)   
  3. return;   
The ProcessStartInfo class will be useful to set information required to start the process. In our example we created a ProcInfo object of type ProcessStartInfo and specified the Copy.bat batch file name through itsFileName parameter. Since the path name is not specified, the “Copy.bat” should reside in the same folder where the executable exists. Next, the arguments (in other words the source and destination file location for the copy operation) is populated into the ProcInfo object through its member Arguments.
  1. //4.2: Populate Process Information   
  2. ProcessStartInfo ProcInfo = new ProcessStartInfo();   
  3. ProcInfo.FileName = "Copy.bat";   
  4. ProcInfo.Arguments = "\"" + txtSrcPath.Text + "\" " + "\"" + txtDestPath.Text + "\"";   
When forming the Argument, note the usage of the escape sequence \” to include the double quote since the path may contains spaces. The Parameter1 and parameter2 are separated by a space when forming the string for Argument member of the ProcessStartInfo class. The following picture shows how the string concatenation is applied.



The Yellow highlighted double quotes are required since some paths may contain spaces. In the preceding picture D:\Temp does not have any space but the path in argument 1 has the space. Since the inputs are taken from the UI, it is advisable to use the escape sequence when forming the Argument string. Parameter1 and parameter2 are separated by a blank space.

Once the ProcessStartInfo structure is ready, we can pass that structure to the Start method call of the Process class. This is shown below.
  1. //4.4: Start the Process and Hook-up process Exit Event   
  2. BatchProc = Process.Start(ProcInfo);   
At this stage, the process will start spawning the console window and excute the Copy.bat. The net effect is, the copy is done based on the parameter specified in the text boxes.

Process – Suppress Background
Sometimes we need to start a process in silent mode. That means, the application responsible for starting the process should not display any background window and the process task should go silent. Setting the hidden WindowStyle to the ProcessStartInfo class can do this. The code for starting the process silent is given below.
  1. //4.3: Start the process in silent Mode3   
  2. if (chkBoxSilent.Checked == true)  
  3. {  
  4.     ProcInfo.WindowStyle = ProcessWindowStyle.Hidden;  
  5. }
Process Exit Notification

In some cases we need to get a notification from the process stating the task completed or process exited. In our case the process exits when the task of copying the file from source to destination is completed. The application starting the process can handle the “Exited“ event of the process to get the notification from the process. The code is given below.
  1. if (chkWhenClosed.Checked == true)   
  2. {  
  3.     BatchProc.EnableRaisingEvents = true;  
  4.     BatchProc.Exited += new System.EventHandler(Batch_Done);  
  5. }  
The handler for the preceding exited event is shown below that displays a message box stating the copy operation has completed.
  1. //Sample 05: Handle Batch completed event   
  2. private void Batch_Done(object sender, EventArgs e)  
  3. {  
  4.     MessageBox.Show("Copy Completed!");  
  5.     BatchProc.Exited -= new System.EventHandler(Batch_Done);  
  6. }  
The entire application can be watched here: Video 1 .

No comments:

Post a Comment