9 out of 20 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.

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Diagnostics.Process

Namespace:  System.Diagnostics
Assembly:  System (in System.dll)
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
[HostProtectionAttribute(SecurityAction.LinkDemand, SharedState = true, Synchronization = true, 
	ExternalProcessMgmt = true, SelfAffectingProcessMgmt = true)]
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
public class Process : Component

The Process type exposes the following members.

  Name Description
Public method Process Initializes a new instance of the Process class.
Top
  Name Description
Public property BasePriority Gets the base priority of the associated process.
Protected property CanRaiseEvents Gets a value indicating whether the component can raise an event. (Inherited from Component.)
Public property Container Gets the IContainer that contains the Component. (Inherited from Component.)
Protected property DesignMode Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public property EnableRaisingEvents Gets or sets whether the Exited event should be raised when the process terminates.
Protected property Events Gets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public property ExitCode Gets the value that the associated process specified when it terminated.
Public property ExitTime Gets the time that the associated process exited.
Public property Handle Gets the native handle of the associated process.
Public property HandleCount Gets the number of handles opened by the process.
Public property HasExited Gets a value indicating whether the associated process has been terminated.
Public property Id Gets the unique identifier for the associated process.
Public property MachineName Gets the name of the computer the associated process is running on.
Public property MainModule Gets the main module for the associated process.
Public property MainWindowHandle Gets the window handle of the main window of the associated process.
Public property MainWindowTitle Gets the caption of the main window of the process.
Public property MaxWorkingSet Gets or sets the maximum allowable working set size for the associated process.
Public property MinWorkingSet Gets or sets the minimum allowable working set size for the associated process.
Public property Modules Gets the modules that have been loaded by the associated process.
Public property NonpagedSystemMemorySize Obsolete. Gets the nonpaged system memory size allocated to this process.
Public property NonpagedSystemMemorySize64 Gets the amount of nonpaged system memory allocated for the associated process.
Public property PagedMemorySize Obsolete. Gets the paged memory size.
Public property PagedMemorySize64 Gets the amount of paged memory allocated for the associated process.
Public property PagedSystemMemorySize Obsolete. Gets the paged system memory size.
Public property PagedSystemMemorySize64 Gets the amount of pageable system memory allocated for the associated process.
Public property PeakPagedMemorySize Obsolete. Gets the peak paged memory size.
Public property PeakPagedMemorySize64 Gets the maximum amount of memory in the virtual memory paging file used by the associated process.
Public property PeakVirtualMemorySize Obsolete. Gets the peak virtual memory size.
Public property PeakVirtualMemorySize64 Gets the maximum amount of virtual memory used by the associated process.
Public property PeakWorkingSet Obsolete. Gets the peak working set size for the associated process.
Public property PeakWorkingSet64 Gets the maximum amount of physical memory used by the associated process.
Public property PriorityBoostEnabled Gets or sets a value indicating whether the associated process priority should temporarily be boosted by the operating system when the main window has the focus.
Public property PriorityClass Gets or sets the overall priority category for the associated process.
Public property PrivateMemorySize Obsolete. Gets the private memory size.
Public property PrivateMemorySize64 Gets the amount of private memory allocated for the associated process.
Public property PrivilegedProcessorTime Gets the privileged processor time for this process.
Public property ProcessName Gets the name of the process.
Public property ProcessorAffinity Gets or sets the processors on which the threads in this process can be scheduled to run.
Public property Responding Gets a value indicating whether the user interface of the process is responding.
Public property SessionId Gets the Terminal Services session identifier for the associated process.
Public property Site Gets or sets the ISite of the Component. (Inherited from Component.)
Public property StandardError Gets a stream used to read the error output of the application.
Public property StandardInput Gets a stream used to write the input of the application.
Public property StandardOutput Gets a stream used to read the output of the application.
Public property StartInfo Gets or sets the properties to pass to the Start method of the Process.
Public property StartTime Gets the time that the associated process was started.
Public property SynchronizingObject Gets or sets the object used to marshal the event handler calls that are issued as a result of a process exit event.
Public property Threads Gets the set of threads that are running in the associated process.
Public property TotalProcessorTime Gets the total processor time for this process.
Public property UserProcessorTime Gets the user processor time for this process.
Public property VirtualMemorySize Obsolete. Gets the size of the process's virtual memory.
Public property VirtualMemorySize64 Gets the amount of the virtual memory allocated for the associated process.
Public property WorkingSet Obsolete. Gets the associated process's physical memory usage.
Public property WorkingSet64 Gets the amount of physical memory allocated for the associated process.
Top
  Name Description
Public method BeginErrorReadLine Begins asynchronous read operations on the redirected StandardError stream of the application.
Public method BeginOutputReadLine Begins asynchronous read operations on the redirected StandardOutput stream of the application.
Public method CancelErrorRead Cancels the asynchronous read operation on the redirected StandardError stream of an application.
Public method CancelOutputRead Cancels the asynchronous read operation on the redirected StandardOutput stream of an application.
Public method Close Frees all the resources that are associated with this component.
Public method CloseMainWindow Closes a process that has a user interface by sending a close message to its main window.
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Dispose() Releases all resources used by the Component. (Inherited from Component.)
Protected method Dispose(Boolean) Infrastructure. Release all resources used by this process. (Overrides Component.Dispose(Boolean).)
Public method Static member EnterDebugMode Puts a Process component in state to interact with operating system processes that run in a special mode by enabling the native property SeDebugPrivilege on the current thread.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public method Static member GetCurrentProcess Gets a new Process component and associates it with the currently active process.
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method Static member GetProcessById(Int32) Returns a new Process component, given the identifier of a process on the local computer.
Public method Static member GetProcessById(Int32, String) Returns a new Process component, given a process identifier and the name of a computer on the network.
Public method Static member GetProcesses() Creates a new Process component for each process resource on the local computer.
Public method Static member GetProcesses(String) Creates a new Process component for each process resource on the specified computer.
Public method Static member GetProcessesByName(String) Creates an array of new Process components and associates them with all the process resources on the local computer that share the specified process name.
Public method Static member GetProcessesByName(String, String) Creates an array of new Process components and associates them with all the process resources on a remote computer that share the specified process name.
Protected method GetService Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method Kill Immediately stops the associated process.
Public method Static member LeaveDebugMode Takes a Process component out of the state that lets it interact with operating system processes that run in a special mode.
Protected method MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected method OnExited Raises the Exited event.
Public method Refresh Discards any information about the associated process that has been cached inside the process component.
Public method Start() Starts (or reuses) the process resource that is specified by the StartInfo property of this Process component and associates it with the component.
Public method Static member Start(ProcessStartInfo) Starts the process resource that is specified by the parameter containing process start information (for example, the file name of the process to start) and associates the resource with a new Process component.
Public method Static member Start(String) Starts a process resource by specifying the name of a document or application file and associates the resource with a new Process component.
Public method Static member Start(String, String) Starts a process resource by specifying the name of an application and a set of command-line arguments, and associates the resource with a new Process component.
Public method Static member Start(String, String, SecureString, String) Starts a process resource by specifying the name of an application, a user name, a password, and a domain and associates the resource with a new Process component.
Public method Static member Start(String, String, String, SecureString, String) Starts a process resource by specifying the name of an application, a set of command-line arguments, a user name, a password, and a domain and associates the resource with a new Process component.
Public method ToString Formats the process's name as a string, combined with the parent component type, if applicable. (Overrides Component.ToString().)
Public method WaitForExit() Instructs the Process component to wait indefinitely for the associated process to exit.
Public method WaitForExit(Int32) Instructs the Process component to wait the specified number of milliseconds for the associated process to exit.
Public method WaitForInputIdle() Causes the Process component to wait indefinitely for the associated process to enter an idle state. This overload applies only to processes with a user interface and, therefore, a message loop.
Public method WaitForInputIdle(Int32) Causes the Process component to wait the specified number of milliseconds for the associated process to enter an idle state. This overload applies only to processes with a user interface and, therefore, a message loop.
Top
  Name Description
Public event Disposed Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public event ErrorDataReceived Occurs when an application writes to its redirected StandardError stream.
Public event Exited Occurs when a process exits.
Public event OutputDataReceived Occurs when an application writes to its redirected StandardOutput stream.
Top
Note Note

Starting with the .NET Framework version 2.0, the ability to reference performance counter data on other computers has been eliminated for many of the .NET Framework methods and properties. This change was made to improve performance and to enable non-administrators to use the Process class. As a result, some applications that did not get exceptions in earlier versions of the .NET Framework may now get a NotSupportedException. The methods and properties affected are too numerous to list here, but the exception information has been added to the affected member topics.

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.

Note Note

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.

Note Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: SharedState | Synchronization | 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.

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


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

namespace MyProcessSample
{
    class MyProcess
    {
        public static void Main()
        {
            Process myProcess = new Process();

            try
            {
                myProcess.StartInfo.UseShellExecute = false;
                // You can start any process, HelloWorld is a do-nothing example.
                myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.Start();
                // This code assumes the process you are starting will terminate itself. 
                // Given that is is started without a window so you cannot terminate it 
                // on the desktop, it must terminate itself or you can do it programmatically
                // from this application using the Kill method.
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}


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
{
    class MyProcess
    {
        // Opens the Internet Explorer application.
        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);
        }

        // Opens urls and .html documents using Internet Explorer.
        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");
        }

        // Uses the ProcessStartInfo class to start new processes,
        // both in a minimized mode.
        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();
        }
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
  • LinkDemand  

    for full trust for the immediate caller. This class cannot be used by partially trusted code.

  • InheritanceDemand  

    for full trust for inheritors. This class cannot be inherited by partially trusted code.

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
MSDN Sample Using PowerShell
<#
.SYNOPSIS
This script creates and starts a Process using .NET
.DESCRIPTION
This script Creates a process object and sets
the executable to notepad. The script then starts
the process.
.NOTES
File Name : Start-Process.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 2.0
.LINK
This script posted to:
http://pshscripts.blogspot.com/2010/05/start-processps1.html
MSDN Sample posted at:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx
.EXAMPLE
When this script runs - you see a copy of notepad popup.
#>

##
# Start of Script
##

# Create a new process object
$Process = new-object System.Diagnostics.Process
try {
$Process.StartInfo.UseShellExecute = $false

# Pick process to start now - for excitement, use notepad.exe
$Process.StartInfo.FileName = "C:\windows\system32\notepad.exe"

# Start process
$Process.Start()
}
catch {
" Error:";$Error[0]
}