Thursday, November 6, 2008
How to launch Window application from C# console application
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.
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.
API Used
- System.Console.WriteLine()
- System.Diagnostics.Process
- Process.Start()
Step by Step process to create a sample application
1. Create a Console project called as InvokeBatchFile.
2. Include the following namespce
Using System.Diagnostics;
3. Add following code for the Main function
Process p = null;
try
{
string targetDir;
targetDir = string.Format(@"C:\ CallBatchFile ");
p = new Process();
p.StartInfo.WorkingDirectory = targetDir;
p.StartInfo.FileName = "MyBatch.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());
}