TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Process Examples (Process.Start)

Create a Process to start external EXEs. Include the System.Diagnostics namespace and call Process.Start.
Process. At winter's end the ice begins to melt. Grass is revealed where snow once was. The temperature rises. This is a process—it has a start and an end. A great change is effected.
Starting processes. In code we model a process. In C# Process.Start (a static method) calls external applications. We can start an EXE as a process.
A project. We add the System.Diagnostics namespace. Our sample project is a C# console application. But these steps will work in many configurations.

Now: Please get Visual Studio set up on the source file. You will need to update some of the paths to make these programs work.

Next: This example sends the C:\ directory name to the operating system. Windows Explorer will open the folder in a new window.

Arguments: The Process.Start method has overloaded forms. So you can call it with more than argument.

C# program that opens directory using System.Diagnostics; class Program { static void Main() { // Use Process.Start here. Process.Start("C:\\"); } }
Text file. In this example on my system, Microsoft Word opens the file example.txt. This is because Word was set as the default .txt editor.

Tip: On many systems, Notepad will instead open the file. The file name is passed to Windows to handle with the default program.

C# program that opens text file using System.Diagnostics; class Program { static void Main() { // Open the file "example.txt". // ... It must be in the same directory as the .exe file. Process.Start("example.txt"); } }
Web browser. This example opens a web address. We specify the URL and send it to Windows. Users might run various browsers, so we do not specify one.

Here: We launch a DuckDuckGo search with a specific query. You can change the address to another location.

Usually: We should not specify a browser. This may make users unhappy. Windows selects the default browser on its own.

C# program that launches web browser using System.Diagnostics; class Program { static void Main() { // Call method. SearchDuckDuckGo("cat pictures"); } static void SearchDuckDuckGo(string term) { // Search DuckDuckGo for this term. Process.Start("https://www.duckduckgo.com/?q=" + term); } }
Microsoft Word. We open Microsoft Word (and other applications from Office) by specifying the EXE name. Here we force Windows to open files in Microsoft Word.

OpenMicrosoftWord: WINWORD.EXE must open the file. Please call OpenMicrosoftWord() with the path of a file.

ProcessStartInfo: In this example we use ProcessStartInfo. In it, we can store a process' properties: details of its execution.

Tip: We could also specify EXCEL.EXE for Microsoft Excel. Or we could use POWERPNT.EXE for PowerPoint.

C# program that starts WINWORD.EXE using System.Diagnostics; class Program { static void Main() { // ... Open specified Word file. OpenMicrosoftWord(@"C:\Users\Sam\Documents\Gears.docx"); } /// <summary> /// Open specified word document. /// </summary> static void OpenMicrosoftWord(string file) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "WINWORD.EXE"; startInfo.Arguments = file; Process.Start(startInfo); } }
Executable. We can run any executable. But we may need to use properties on ProcessStartInfo. Here we run a program called dcm2jpg.exe—it converts a certain image format.

Part 1: This example first creates a ProcessStartInfo. We use CreateNoWindow and UseShellExecute to control some command-line options.

Part 2: We set some arguments to indicate to the executable what directories were are using.

Part 3: We invoke Process.Start, and then call WaitForExit to wait for the executable to finish its task.

C# program that runs EXE using System.Diagnostics; class Program { static void Main() { LaunchCommandLineApp(); } static void LaunchCommandLineApp() { const string ex1 = "C:\\"; const string ex2 = "C:\\Dir"; // Part 1: use ProcessStartInfo class. ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = "dcm2jpg.exe"; startInfo.WindowStyle = ProcessWindowStyle.Hidden; // Part 2: set arguments. startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2; try { // Part 3: start with the info we specified. // ... Call WaitForExit. using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); } } catch { // Log error. } } }
GetProcesses. This gets an array of all the processes currently open on the System. We can loop over and test for running programs.

Note: Process.GetProcesses looks at all processes currently running. With this method, we enumerate the active processes.

Info: GetProcesses receives no arguments or one argument of the target machine name (not shown). It returns a Process array.

Foreach: We use a foreach-loop to access all the Processes returned by the method. We access each Process's Id.

Foreach
C# program that uses GetProcesses method using System; using System.Diagnostics; class Program { static void Main() { // Show all processes on the local computer. Process[] processes = Process.GetProcesses(); // Display count. Console.WriteLine("Count: {0}", processes.Length); // Loop over processes. foreach (Process process in processes) { Console.WriteLine(process.Id); } } } Output Count: 70 388 5312 1564 972 2152 936 3132....
GetProcessesByName. This method returns an array of Process objects. Its functionality can be derived by combining other methods such as GetProcesses.

Here: We use Process.GetProcessesByName in a while-true loop. We use the argument "chrome" to GetProcessesByName.

While

Name: This returns an array of all processes with name "chrome." Then, we sleep for 5 seconds before calling the method again.

Sleep

Result: Because of its multi-process model, Chrome can run in several processes at once.

Tip: Avoid the "exe" part. The method did not work when I tried using the string "chrome.exe" as the argument.

C# program that uses GetProcessesByName using System; using System.Diagnostics; using System.Threading; class Program { static void Main() { while (true) { // Omit the exe part. Process[] chromes = Process.GetProcessesByName("chrome"); Console.WriteLine("{0} chrome processes", chromes.Length); Thread.Sleep(5000); } } } Output 0 chrome processes 3 chrome processes 4 chrome processes 5 chrome processes 5 chrome processes 5 chrome processes
RedirectStandardOutput. With this property (found on ProcessStartInfo) we can redirect the standard output of Process. We can see program output within another program.

Info: RedirectStandardOutput eliminates the need for output files. It allows us to use a console program directly inside a C# program.

StreamReader: We redirect into a StreamReader. With ReadToEnd() we can read the entire output of an EXE into a string.

StreamReader

Tip: To redirect the output of a process, set UseShellExecute to false and RedirectStandardOutput to true.

Also: You must specify the file name (with the FileName property) before calling Process.Start.

C# program that redirects standard output using System; using System.Diagnostics; using System.IO; class Program { static void Main() { // // Set up the process with the ProcessStartInfo class. // ProcessStartInfo start = new ProcessStartInfo(); start.FileName = @"C:\7za.exe"; // Specify exe name. start.UseShellExecute = false; start.RedirectStandardOutput = true; // // Start the process. // using (Process process = Process.Start(start)) { // // Read in all the text from the process with the StreamReader. // using (StreamReader reader = process.StandardOutput) { string result = reader.ReadToEnd(); Console.Write(result); } } } } Output 7-Zip (A) 4.60 beta Copyright (c) 1999-2008 Igor Pavlov 2008-08-19 Usage: 7za <command> [<switches>...] <archive_name> [<file_names>...] [<@listfiles...>]
Kill. It is possible to Kill or terminate a Process that we acquire a reference to. The process is not given a chance to continue running.

Example: We start the Notepad program, and then wait one second. Finally, we call the Kill method on the process variable.

Tip: It is probably more common to use the Kill method to search for and stop applications that are not working.

So: First loop through the running processes. Then, you can acquire a reference to the process and call Kill.

C# program that uses Process Kill method using System.Diagnostics; using System.Threading; class Program { static void Main() { // Start notepad. Process process = Process.Start("notepad.exe"); // Wait one second. Thread.Sleep(1000); // End notepad. process.Kill(); } }
ProcessStartInfo. This is a class in System.Diagnostics. It stores information about the process—specifically how the process is started and its configuration.
Process FileName. This is a property that indicates the program or file you want to run. It can be a program such as "WINWORD.EXE". Sometimes we can just specify a file name.
Process Arguments. Thir property stores the arguments, such as -flags or filename. This is a string property. We can assign a string to it.
Window properties. CreateNoWindow allows you to silently run a command line program. It does not flash a console window. Use WindowStyle to set windows as hidden.
Static methods. Many methods are available on the Process type. Some are instance (called on the instance) and others are static (called on the type).Static Method
Main. We can combine the Process.Start method with a console program that receives a parameter list. The program handles a string args array on invocation.Main args
7-Zip. We can use this free compression utility with Process.Start. The code is fairly simple. We can adjust command-line options to the 7-Zip executable.7-Zip Executable
ThreadPool. This type facilitates threading. Please see the tutorial with ThreadPool and progress bars. An EXE can run concurrently over more than one processor.ThreadPool
A review. The Process type allows an external access to the operating system. With Process, we can run any EXE. We can pass command-line arguments to these programs.
System.Diagnostics. This namespace makes many things possible. With Process.Start, we can run separate programs concurrently with no threading constructs.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf