Launch Windows applications or CallBatch files from a C#.NET console application

Started by shrutika, Feb 23, 2009, 02:05 PM

Previous topic - Next topic

shrutika


Introduction
This article is targeted for mid-level programmers who have already worked on C# language. This article uses batch files for demonstration and the reader should have preliminary knowledge of batch files.

Technology Used
Sample application describes how to call any Windows application or batch file using a C# console application. This application launches a new process and executes Windows applications in that process.

Demonstration of passing parameters to the batch file and accessing passed parameters in a batch file

API Used

  • System.Console.WriteLine()
  • System.Diagnostics.Process
  • Process.Start()
Using the code
Step by Step process to create a sample application

  • Step 1
Create a Console project called as CallBatchFile.



Your directory structure created would be like this after clicking the OK button:





  • Step 2
Include the following namespace for the Process class:

                   using System.Diagnostics;


  • Step 3
[/b]
Add the following code for the Main function:

Process p=null;
try
{
    string targetDir;
    targetDir = string.Format(@"C:\Temp\CallBatchFile\BatchFile");
    p= new Process();
    p.StartInfo.WorkingDirectory = targetDir;
    p.StartInfo.FileName = "MyBatchFile.bat";

    p.StartInfo.Arguments =  string.Format("C-Sharp Console application");
    p.StartInfo.CreateNoWindow = false;
    p.Start();
    p.WaitForExit();
}
catch (Exception ex)
{
    Console.WriteLine("Exception Occurred :{0},{1}",
              ex.Message,ex.StackTrace.ToString());
}


Explanation about code
targetDir is a local variable which stores the directory path for the batch file to execute. ProcessStartInfo class (p.StartInfo) has workingDirectory, FileName, Arguments, and CreateNoWindow properties for the new process. Start() function will start the process. WaitForExit function will make sure that process will wait till it finishes its processing.


  • Step 4
The whole program will be like this:

using System;
using System.Diagnostics;

namespace CallBatchFile
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class Class1
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Process p=null;
            try
            {
                string targetDir;
                targetDir =
                  string.Format(@"C:\Temp\CallBatchFile\BatchFile");
                p= new Process();
                p.StartInfo.WorkingDirectory = targetDir;
                p.StartInfo.FileName = "MyBatchFile.bat";

                p.StartInfo.Arguments =
                  string.Format("C-Sharp Console application");
                p.StartInfo.CreateNoWindow = false;
                p.Start();
                p.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}",
                            ex.Message,ex.StackTrace.ToString());
            }
        }
    }
}



  • Step 5

Configuration: Create a new directory called as BatchFile to the patch c:\temp\CallBatchFile. Your new directory structure would be like below:





  • Step 6
Create a new batch file called as MyBatchFile.bat and add the following lines:

@echo off
Echo Hello word ! From %1
Pause


First line is for Echo off  which will make sure that the batch file will not print each line on the screen while file is executing. Second line will print Hello world  ! with %1 (the parameter passed to the batch file). Third line is to pause the execution of the batch file.


  • Step 7

Compile the program and execute it. You should see the following result:



There are two windows created: one for the console application called CallBatchFile.exe and another for the new process where we are trying to execute the batch file.

Note: Remember we have earlier used p.StartInfo.CreateNoWindow=false, but still the new window is coming. This is because the batch file has pause command and it needs user's intervention to continue the execution.

Calling Notepad using the same program
Change Step 3 code as mentioned below:

Process p=null;
    try
    {
        p= new Process();
        p.StartInfo.FileName = "notepad";
        p.Start();
        p.WaitForExit();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception Occurred :{0},{1}",
                 ex.Message,ex.StackTrace.ToString());
    }


This will open Notepad.