15 out of 23 rated this helpful - Rate this topic

Process Class

Provides access to local and remote processes and enables you to start and stop local system processes.

Namespace: System.Diagnostics
Assembly: System (in system.dll)

public class Process : Component
public class Process extends Component
public class Process extends Component
NoteNote

The HostProtectionAttribute attribute applied to this class has the following Resources property value: Synchronization | SharedState | ExternalProcessMgmt | SelfAffectingProcessMgmt. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

A Process component provides access to a process that is running on a computer. A process, in the simplest terms, is a running application. A thread is the basic unit to which the operating system allocates processor time. A thread can execute any part of the code of the process, including parts currently being executed by another thread.

The Process component is a useful tool for starting, stopping, controlling, and monitoring applications. Using the Process component, you can obtain a list of the processes that are running, or you can start a new process. A Process component is used to access system processes. After a Process component has been initialized, it can be used to obtain information about the running process. Such information includes the set of threads, the loaded modules (.dll and .exe files), and performance information such as the amount of memory the process is using.

If you have a path variable declared in your system using quotes, you must fully qualify that path when starting any process found in that location. Otherwise, the system will not find the path. For example, if c:\mypath is not in your path, and you add it using quotation marks: path = %path%;"c:\mypath", you must fully qualify any process in c:\mypath when starting it.

The process component obtains information about a group of properties all at once. After the Process component has obtained information about one member of any group, it will cache the values for the other properties in that group and not obtain new information about the other members of the group until you call the Refresh method. Therefore, a property value is not guaranteed to be any newer than the last call to the Refresh method. The group breakdowns are operating-system dependent.

A system process is uniquely identified on the system by its process identifier. Like many Windows resources, a process is also identified by its handle, which might not be unique on the computer. A handle is the generic term for an identifier of a resource. The operating system persists the process handle, which is accessed through the Handle property of the Process component, even when the process has exited. Thus, you can get the process's administrative information, such as the ExitCode (usually either zero for success or a nonzero error code) and the ExitTime. Handles are an extremely valuable resource, so leaking handles is more virulent than leaking memory.

NoteNote

This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see Link Demands and Inheritance Demands.

The following example uses an instance of the Process class to start a process.

using System;
using System.Diagnostics;
using System.ComponentModel;

namespace MyProcessSample
{
	/// <summary>
	/// Shell for the sample.
	/// </summary>
	class MyProcess
	{
		// These are the Win32 error code for file not found or access denied.
		const int ERROR_FILE_NOT_FOUND =2;
		const int ERROR_ACCESS_DENIED = 5;

		/// <summary>
		/// Prints a file with a .doc extension.
		/// </summary>
		void PrintDoc()
		{
			Process myProcess = new Process();
			
			try
			{
				// Get the path that stores user documents.
				string myDocumentsPath = 
					Environment.GetFolderPath(Environment.SpecialFolder.Personal);

				myProcess.StartInfo.FileName = myDocumentsPath + "\\MyFile.doc"; 
				myProcess.StartInfo.Verb = "Print";
				myProcess.StartInfo.CreateNoWindow = true;
				myProcess.Start();
			}
			catch (Win32Exception e)
			{
				if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
				{
					Console.WriteLine(e.Message + ". Check the path.");
				} 

				else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
				{
					// Note that if your word processor might generate exceptions
					// such as this, which are handled first.
					Console.WriteLine(e.Message + 
						". You do not have permission to print this file.");
				}
			}
		}


		public static void Main()
		{
			MyProcess myProcess = new MyProcess();
			myProcess.PrintDoc();
		}
	}
}

The following example uses the Process class itself and a static Start method to start a process.

using System;
using System.Diagnostics;
using System.ComponentModel;

namespace MyProcessSample
{
	/// <summary>
	/// Shell for the sample.
	/// </summary>
	class MyProcess
	{
	   
		/// <summary>
		/// Opens the Internet Explorer application.
		/// </summary>
		void OpenApplication(string myFavoritesPath)
		{
			// Start Internet Explorer. Defaults to the home page.
			Process.Start("IExplore.exe");
				    
		    // Display the contents of the favorites folder in the browser.
		    Process.Start(myFavoritesPath);
 
		}
		
		/// <summary>
		/// Opens urls and .html documents using Internet Explorer.
		/// </summary>
		void OpenWithArguments()
		{
			// url's are not considered documents. They can only be opened
			// by passing them as arguments.
			Process.Start("IExplore.exe", "www.northwindtraders.com");
			
			// Start a Web page using a browser associated with .html and .asp files.
			Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm");
			Process.Start("IExplore.exe", "C:\\myPath\\myFile.asp");
		}
		
		/// <summary>
		/// Uses the ProcessStartInfo class to start new processes, both in a minimized 
		/// mode.
		/// </summary>
		void OpenWithStartInfo()
		{
			
			ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
			startInfo.WindowStyle = ProcessWindowStyle.Minimized;
			
			Process.Start(startInfo);
			
			startInfo.Arguments = "www.northwindtraders.com";
			
			Process.Start(startInfo);
			
		}

		static void Main()
		{
            		// Get the path that stores favorite links.
            		string myFavoritesPath = 
                	Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
                
            		MyProcess myProcess = new MyProcess();
         
			myProcess.OpenApplication(myFavoritesPath);
			myProcess.OpenWithArguments();
			myProcess.OpenWithStartInfo();

       		}	
	}
}

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Reading StdErr and StdOut

Often one would like to read both StdErr and StdOut from a process. However, the documentation notes that, "A deadlock condition results if the parent process calls p.StandardOutput.ReadToEnd followed by p.StandardError.ReadToEnd and the child process writes enough text to fill its error stream. The parent process would wait indefinitely for the child process to close its StandardOutput stream. The child process would wait indefinitely for the parent to read from the full StandardError stream. You can use asynchronous read operations to avoid these dependencies and their deadlock potential. Alternately, you can avoid the deadlock condition by creating two threads and reading the output of each stream on a separate thread.". Below is some code to avoid the deadlock.

using System;
using System.Diagnostics;
namespace NS
{
/// <summary>
/// This class handles stderr and stdout for a process.
/// </summary>
public class ProcessOutputHandler
{
private Process proc;
/// <summary>
/// The constructor requires a reference to the process that will be read.
/// The process should have .RedirectStandardOutput and .RedirectStandardError set to true.
/// </summary>
/// <param name="process">The process that will have its output read by this class.</param>
public ProcessOutputHandler(Process process)
{
proc = process;
Debug.Assert(proc.StartInfo.RedirectStandardError, "RedirectStandardError must be true to use ProcessOutputHandler.");
Debug.Assert(proc.StartInfo.RedirectStandardOutput, "RedirectStandardOut must be true to use ProcessOutputHandler.");
}
  /// <summary>
/// This method starts reading the standard error stream from Process.
/// </summary>
public void ReadStdErr()
{
try
{
string line;
while ((!proc.HasExited) && ((line = proc.StandardError.ReadLine()) != null))
Console.WriteLine(line);
}
catch (InvalidOperationException)
{
// The process has exited or StandardError hasn't been redirected.
}
}
  /// <summary>
/// This method starts reading the standard output sream from Process.
/// </summary>
public void ReadStdOut()
{
try
{
string line;
while ((!proc.HasExited) && ((line = proc.StandardOutput.ReadLine()) != null))
Console.WriteLine(line);
}
catch (InvalidOperationException)
{
// The process has exited or StandardError hasn't been redirected.
}
}
}
 private void runProcess(string FileName, string Arguments)
{
// prep process
ProcessStartInfo psi = new ProcessStartInfo(FileName, Arguments);
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
  // start process
using (Process process = new Process())
{
// pass process data
process.StartInfo = psi;
   // prep for multithreaded logging
ProcessOutputHandler outputHandler = new ProcessOutputHandler(process);
Thread stdOutReader = new Thread(new ThreadStart(outputHandler.ReadStdOut));
Thread stdErrReader = new Thread(new ThreadStart(outputHandler.ReadStdErr));
   // start process and stream readers
process.Start();
stdOutReader.Start();
stdErrReader.Start();
   // wait for process to complete
process.WaitForExit();
}
}
}
}
StdErr and StdOut--a plug-and-play

I have converted the useful code ideas presented by fatcat1111 into a practical library module that allows you to selectively grab the stdout or stderr streams and use them in your program, rather than just displaying them on the console. My class--CleanCode.IO.ExecProcess--is documented at http://cleancode.sourceforge.net/api/csharp/CleanCode.IO.ExecProcess.html (or if you prefer, as I do, the API navigator, use http://cleancode.sourceforge.net/api/csharp/index.html). The source and binary may be downloaded from http://cleancode.sourceforge.net/wwwdoc/download.html; just follow the couple links to the csharp zip file.

Since I needed to do this myself, I thought I might save others some time by posting this here.