C# Process

Array Collections File Keyword String .NET Cast Class Compression Data Directive Enum Exception If Interface Lambda LINQ Loop Method Number Process Property Regex Sort StringBuilder Struct Switch Time Windows WPF

Process

A Process starts,
dies,
and does something in between. The Process.Start method calls external applications. It allows users to view documents and web pages. It also executes EXE programs and command line utilities.

Start

To start, we add the System.Diagnostics namespace. Our sample project is a C# console application. But these steps will work in many configurations. Please get Visual Studio set up on the source file.

C# programming language

Next:This example sends the C:\ directory name to the operating system, which will result in Explorer opening the folder on your desktop.

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

Program that opens directory: C#

using System.Diagnostics;

class Program
{
    static void Main()
    {
	// Use Process.Start here.
	Process.Start("C:\\");
    }
}

Text file

File

Continuing on, you can specify the file name alone. In this example on my system, Microsoft Word opens the file example.txt, because on the system Microsoft Word is 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.

Program that opens text file: C#

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

Google search engine

Next we specify the URL and send it to Windows. Here we launch a Google search for some search terms. Our users might run various browsers including Firefox, Google Chrome, Internet Explorer and Opera.

Note:You should usually not specify a browser. It may make users unhappy. Windows selects the default browser on its own.

Program that launches web browser: C#

using System.Diagnostics;

class Program
{
    static void Main()
    {
	// Search Google for this.
	SearchGoogle("VB.NET awesome");
    }

    /// <summary>
    /// Search Google for this term.
    /// </summary>
    static void SearchGoogle(string t)
    {
	Process.Start("http://google.com/search?q=" + t);
    }
}

Microsoft Word

Method

We open Microsoft Word (and other applications from Office) by specifying the EXE name. Here we force Windows to open files in Microsoft Word. 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.

Program that starts WINWORD.EXE: C#

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

Here we see an incomplete listing of Process properties. You will use most of these when starting programs from your program. Knowing about all of them is valuable. But often we do not need many of them.

Net

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 file such as "example.txt". It can be a program such as "WINWORD.EXE".

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. I have used ProcessWindowStyle.Hidden often.

UserName, WorkingDirectory, Domain:These control OS-specific parameters—for more complex situations.

EXE

Program

We can run any executable, but may need to use more properties of ProcessStartInfo. Here we run an old program called dcm2jpg.exe. This program converts DICOM images back and forth. The example is a bit more complicated.

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

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

Program that runs EXE: C#

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

Method

Many methods are available on the Process type. Some are instance (called on the instance) and others are static (called on the type). As usual they are simple to use once you have used them before.

Kill:It is also 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.

GetProcesses

GetProcessesByName:This returns processes with a specific associated name. It is mainly a convenience method.

GetProcessesByName

RedirectStandardOutput:We can redirect the standard output of Process using RedirectStandardOutput on ProcessStartInfo.

RedirectStandardOutput

Main

Main method

We can combine the Process.Start method with a console program that receives a parameter list from a string[] args method on invocation. We must specify and test the string array parameter in the Main method.

Main, Args

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

Discussion

Convert

Here we point to some other resources on this web site regarding processes on Windows. I have used Windows EXE bundling more than once. Please note the article about how to put 7-Zip in a Windows Forms program.

7-Zip Executable7-Zip Command-Line

ThreadPool:Please see my work with ThreadPool and progress bars. I made an EXE run concurrently over more than one processor.

ThreadPool

Summary

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. This makes many things possible.

C#