Click here to Skip to main content
Click here to Skip to main content

How to launch Windows applications (Notepad) / Call Batch files from a C#/.NET console application.

, 12 Apr 2005
Rate this:
Please Sign up or sign in to vote.
How to launch a Windows application (Notepad) / Call Batch files from a C#/.NET console application.

console Application calling notepad

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.

    CreateConsoleproject

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

    CreateConsoleproject

  • Step 2

    Include the following namespace for the Process class:

    using System.Diagnostics;
  • Step 3

    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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Harish Shikhare
Web Developer
United States United States
Microsoft solution Developer since 1996. Worked on different technolgies including but not limited to Visual Studio .NET , ASP .NET , C# Visual C++ , MFC , COM , DCOM ,OLE.
 
Expertiesed on different industry sectors of software development such as system softwares (worked for Intel and Microsoft ),application softwares (Manufacturing,Financial,Security,Airline industry, Multimedia)
 

Site developer for religious community in his spare time http://www.trimbakeshwar.net
 

 

 


Comments and Discussions

 
QuestionRe: open notepad Pinmemberpingponggirl23-Aug-06 8:03 
AnswerRe: open notepad Pinmemberdaluu28-Aug-06 9:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 12 Apr 2005
Article Copyright 2005 by Harish Shikhare
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid