Overview
Sometimes,
we will need to validate the current state of a system service/process, prior
during and after a test execution. the following paragraphs will provide the
basic set of tools to accomplish these tasks.
Note!
To
use the system services, you first need to add the "System.ServiceProcess"
as a reference and the "System.Diagnostics" namespace.

Getting the basic information about a service
static
void Main(string[] args)
{
//Define the service that we want to use
ServiceController sc = new ServiceController("Spooler");
//Getting the service status
string
servicestatus = sc.Status.ToString();
//Getting the service name
string
servicename = sc.ServiceName;
//Getting the service Display Name
string
servicedisplayname = sc.DisplayName;
}
Getting the basic information about a process
//Selecting the process by ID
Process Process = Process.GetProcessById(94204);
//Get the process name
string
processname = Process.ProcessName;
How to
change the service status
In the following code snippet, I will
demonstrate how to "Start" and "Stop" a specific service
static
void Main(string[] args)
//Define the service that we want to use
ServiceController Service = new
ServiceController("Spooler");
//Define a Time Span that we will use to validate the service status
TimeSpan Timer = TimeSpan.FromMilliseconds(30);
//Start a Service
Service.Start();
Service.WaitForStatus(ServiceControllerStatus.Running,Timer);
//Stop a Service
Service.Stop();
Service.WaitForStatus(ServiceControllerStatus.Stopped, Timer);
}
How to kill a process execution
For
this purposes, we will use the "Kill" command.
//Selecting the process by ID
Process Process = Process.GetProcessById(94204);
//Kill the process
Process.Kill();
great
ReplyDelete