Introduction
In this article we will build a very simple Windows Console Application that will start a process.
Let me tell you one thing, that this is just a demo application whose actual intention is just to demonstrate application of the "ProcessStartInfo" Class and the "Process" class.
In future articles you will see the advanced implementation of these classes.
Procedures
Step 1: Create a new “Windows Console Application” in Visual Studio and name it as you choose (I here named it ProStartDemo).
Now a new Program.cs is created.
Step 2: Add the following using directive (assembly reference) :
using System.Diagnostics;
Step 3: Now add the following code:
static void Main(string[] args)
{
string myChoice;
Console.WriteLine("Would you Like to Start CMD?");
Console.WriteLine("\nPress Y(Yes) to start theCMD...");
//Storing the User Choice into a string type
//variable 'myChoice'
myChoice= Console.ReadLine();
//Starting a Switch-Case Condition Cheking
switch(myChoice)
{
//If user Enter Y then Call the
// StartProcess() Method
case "Y":
StartProcess();
break;
default:
//Otherwise just Print The Error Message
Console.WriteLine("You have Enetered the Wrong Key.");
Console.ReadKey();
break;
}
}
private static void StartProcess()
{
//Setting an instance of ProcessStartInfo class
// under System.Diagnostic Assembly Reference
ProcessStartInfo pro = new ProcessStartInfo();
//Setting the FileName to be Started like in our
//Project we are just going to start a CMD Window.
pro.FileName = "cmd.exe";
//Instead of using the above two line of codes, You
// can just use the code below:
// ProcessStartInfo pro = new ProcessStartInfo("cmd.exe");
//Creating an Instance of the Process Class
// which will help to execute our Process
Process proStart = new Process();
//Setting up the Process Name here which we are
// going to start from ProcessStartInfo
proStart.StartInfo = pro;
//Calling the Start Method of Process class to
// Invoke our Process viz 'cmd.exe'
proStart.Start();
}
Step 4: Compile your project and run it. You will see that when you enter your choice as "Y" in the Console window you will get the Cmd window appear.
Step 5: One thing you should notice is that when the CMD window appears it shows a default path (that is actually the path where your project is associated).
To override this default path you need to just add a single line of code just before instantiating the Process class.
//Setting up the Working Directory
pro.WorkingDirectory = @"C:\";
Here instead of “C:\” you can add whatever the path you may want.
Now after setting this, compile your project and run it.
Now when you enter your choice as "Y", you will get the CMD window open but with a different path.
That's all for this article. I am embedding the source file so that you can go through it.