C#

.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda LINQ Parse Path Process Property Regex Replace Row Sort Split Static StringBuilder Substring Switch Tuple

Process. A process starts, dies, and does something in between. With processes, we run separate programs at the level of the operating system.
Start, a static method, calls external applications. It allows users to view documents and web pages. It also executes EXE programs and command-line utilities.
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.

Based on: .NET 4.5

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 (Firefox, Google Chrome, Internet Explorer).

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

Note: We should usually 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()
    {
	// Search Google for this.
	SearchGoogle("cat pictures");
    }

    /// <summary>
    /// Search Google for this term.
    /// </summary>
    static void SearchGoogle(string t)
    {
	Process.Start("http://google.com/search?q=" + t);
    }
}
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);
    }
}
Properties. To refresh our memory, here is a partial listing of Process properties. We will use most of these when starting programs from a program.

ProcessStartInfo: Stores information about the process—specifically how the process is started and its configuration.FileName: The program or filename you want to run. It can be a program such as "WINWORD.EXE". Sometimes we can just specify a file name.Arguments: Stores the arguments, such as -flags or filename. This is a string property.CreateNoWindow: Allows you to silently run a command line program. It does not flash a console window.WindowStyle: Use this to set windows as hidden. ProcessWindowStyle.Hidden is often useful.UserName, WorkingDirectory, Domain: These control OS-specific parameters—for more complex situations.


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.

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

Note 2: The program we are running is called dcm2jpg.exe, and the Arguments string is set.

C# program that runs EXE

using System.Diagnostics;

class Program
{
    static void Main()
    {
	LaunchCommandLineApp();
    }

    /// <summary>
    /// Launch the legacy application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
	// For the example.
	const string ex1 = "C:\\";
	const string ex2 = "C:\\Dir";

	// Use ProcessStartInfo class.
	ProcessStartInfo startInfo = new ProcessStartInfo();
	startInfo.CreateNoWindow = false;
	startInfo.UseShellExecute = false;
	startInfo.FileName = "dcm2jpg.exe";
	startInfo.WindowStyle = ProcessWindowStyle.Hidden;
	startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

	try
	{
	    // Start the process with the info we specified.
	    // Call WaitForExit and then the using-statement will close.
	    using (Process exeProcess = Process.Start(startInfo))
	    {
		exeProcess.WaitForExit();
	    }
	}
	catch
	{
	    // Log error.
	}
    }
}
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
Kill. Violence is not the answer—unless a process is really annoying. It is possible to Kill or terminate a Process that we acquire a reference to.Kill
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
(... Rest of output was omitted for brevity.)
GetProcesses, usage. What are some real-world uses for the Process.GetProcesses method? We can develop a program that monitors memory usage of processes on a computer.

Then: We can test memory usage, gathering and recording statistics. This reveals memory growth over time.


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.

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

WhileSleep
C# 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
GetProcessesByName, usage. While running the above program, I opened Chrome with several tabs. You can see that Chrome created up to five processes during this.

Note: 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.


RedirectStandardOutput. With this property (found on ProcessStartInfo) we can redirect the standard output of Process. We can see program output within another program.RedirectStandardOutput
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

Tip: In the Main method, we can test the string array parameter. There are some quirks to know about empty arguments.

Tip 2: With Main() and Process.Start, two C# programs can interact with each other with no code access.


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 Executable7-Zip Command-Line
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.