Dynamically create Servicecontroller array

Asked

Viewed 56 times

1

I would like to create a Windows service monitoring and I want to register a customizable amount of services. For this I need to have a Servicecontroller array dynamically, the problem is that of Exception when I try to assign the service name to the Servicename property.

Follow an example below:

//Eu declaro uma variável global
ServiceController[] scService;

//Aqui vai o código que busca os serviços e põe em um Array de String

//aí o contaService tem a quantidade de serviços cadastrados
scService = new ServiceController[contaService];

//Agora quando vou dar o nome aos servicos
for (int i = 0; i < contaService; i++)
{
    //Nessa linha da exception
    scService[i].ServiceName = scNome[i];
}
  • And what’s the mistake?

  • Looking at the code is probably Null Excption error, probably forgot to assign or instantiate scService.

  • Yes, it is Nullreferenceexception

  • @Ro_geek put an answer right below, try to use in your code.

2 answers

1

The correct is to instantiate in the For loop, passing the names as parameter for each Array item:

//Eu declaro uma variável global
ServiceController[] scService;

//Aqui vai o código que busca os serviços e põe em um Array

//Tira a linha que instancia array dos objetos vazios
//scService = new ServiceController[contaService];

//Agora quando vou dar o nome aos servicos
for (int i = 0; i < contaService; i++)
{
    //Alterei a linha da exception
    //scService[i].ServiceName = scNome[i];
    //Para a linha abaixo
    scService[i] = new ServiceController(scValor[i]);
}

0


You forgot to instantiate the vectors before so is giving the Null Excption, try to put this before:

scService[i] = new ServiceController("Simple Service");

Or:

scService[i] = ServiceController.GetServices();
  • @Khaosdoctor I did this, the author clarified the error, and my answer is not incorrect..

  • You gave me a good idea. Can be considered the answer, yes!

  • If considered evaluate the question =). Vlw and good luck.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.