Selenium C# Tutorial: Working with Process and Services
Updated: Mar 5
Sometimes, we will need to validate a system service/process's state prior and after test execution. This article will provide the basic set of tools to accomplish these tasks.
Note: To use the system services/Process, you first need to add the "System.ServiceProcess" as a reference and the "System. Diagnostics" namespace.
Working with services
public class Program
{
static void Main(string[] args)
{
//Define the service that we want to use
ServiceController SpoolerService = new ServiceController("Spooler");
//Define a TimeSpan that we will use to validate the service status
TimeSpan Timer = TimeSpan.FromMilliseconds(30);
//Start a Service
SpoolerService.Start();
SpoolerService.WaitForStatus(ServiceControllerStatus.Running, Timer);
//Stop a Service
SpoolerService.Stop();
SpoolerService.WaitForStatus(ServiceControllerStatus.Stopped, Timer);
//Getting the service status
Console.WriteLine(SpoolerService.Status);
//Getting the service name
Console.WriteLine(SpoolerService.ServiceName);
//Getting the service Display Name
Console.WriteLine(SpoolerService.DisplayName);
//Name of the host ("." is for the local computer)
Console.WriteLine(SpoolerService.MachineName);
//Get all service Dependencies
ServiceController[] Dependencis = SpoolerService.DependentServices;
foreach (var item in Dependencis)
{
Console.WriteLine(item.DisplayName);
}
//Get the type of service
Console.WriteLine(SpoolerService.ServiceType);
//How to run a specific program
WorkingWithProcess.StartInfo.FileName = "notepad.exe";
//Selecting the process by ID
Process Process = Process.GetProcessById(94204);
//Kill the process
Process.Kill();
}
}