Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Article

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

Rate me:
Please Sign up or sign in to vote.
3.88/5 (24 votes)
12 Apr 20052 min read 257.9K   2.2K   55   14
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:

    C#
    using System.Diagnostics;
  • Step 3

    Add the following code for the Main function:

    C#
    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:

    C#
    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:

    Image 4

  • 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:

    Image 5

    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:

C#
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


Written By
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

 
QuestionExecuting batch file from C# Process Pin
VicQA18-Aug-16 6:06
VicQA18-Aug-16 6:06 
Questionthanks Pin
sukhen dass4-Jan-15 7:54
sukhen dass4-Jan-15 7:54 
GeneralMy vote of 2 Pin
#realJSOP6-Jan-09 8:11
mve#realJSOP6-Jan-09 8:11 
GeneralRe: My vote of 2 Pin
Your Display Name Here29-Jan-10 3:48
Your Display Name Here29-Jan-10 3:48 
Generalpassing the values Pin
rameshdontagani10-Oct-07 19:58
rameshdontagani10-Oct-07 19:58 
GeneralPassing more than 2 parameters to the batch file Pin
depz7-Oct-07 23:27
depz7-Oct-07 23:27 
QuestionCan I run the files on a Remote Server? Pin
Shereesh20-Oct-06 10:55
Shereesh20-Oct-06 10:55 
GeneralShellExecute Pin
Bjornar16-Apr-06 14:14
Bjornar16-Apr-06 14:14 
If you are not interested in knowing when your spawned application has ended, invoke the ShellExecute function to run any file target, that is, if executable it will run, or if it is a registered file type, it will be run by registered handler application. Then you need not hardcode any application such as notepad.

public class Shell32
{
[DllImport("shell32.dll")]
public static extern IntPtr ShellExecute(IntPtr hwnd,
[MarshalAs(UnmanagedType.LPStr)]string lpOperation,
[MarshalAs(UnmanagedType.LPStr)]string lpFile,
[MarshalAs(UnmanagedType.LPStr)]string lpParameters,
[MarshalAs(UnmanagedType.LPStr)]string lpDirectory,
int nShowCmd);
};

...

Shell32.ShellExecute( ownerHandle, "open", pathToWhateverTargetFileOrLink, "", "", 0 );
Questionhidding called application and piping output Pin
daluu11-Jan-06 14:21
daluu11-Jan-06 14:21 
AnswerRe: hidding called application and piping output Pin
Armand Molinski26-Aug-06 1:08
Armand Molinski26-Aug-06 1:08 
Generalopen notepad Pin
lakshmi patil28-Dec-05 0:43
lakshmi patil28-Dec-05 0:43 
GeneralRe: open notepad in web application Pin
daluu11-Jan-06 14:13
daluu11-Jan-06 14:13 
QuestionRe: open notepad Pin
pingponggirl23-Aug-06 8:03
pingponggirl23-Aug-06 8:03 
AnswerRe: open notepad Pin
daluu28-Aug-06 9:14
daluu28-Aug-06 9:14 

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

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