Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.ServiceProcess ServiceController in .NETCore

Tags:

.net-core

I want to control a MySQL service from a .NETCore project. I was able to do this in a .NETFramework 4.7 project with a reference to System.ServiceProcess.dll. .NETCore projects seem to use a different System.ServiceProcess.dll which has less functionality.

Is there a different way to control a MySQL service using .NETCore? Can I just reference the .NETFramework dll from a .NETCore project?

like image 810
user2687412 Avatar asked Sep 06 '25 03:09

user2687412


1 Answers

I make it work. It's as follows:

  1. Install System.ServiceProcess.ServiceController package using nuget from Visual Studio (Tools > Nuget Package Manager > Manage Nuget Packages for Solution)
  2. Use the following code as example. This link will explain how to use the code: https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontroller.start?view=dotnet-plat-ext-6.0

Check whether the Alerter service is started.

ServiceController sc  = new ServiceController();
sc.ServiceName = "Alerter";
Console.WriteLine("The Alerter service status is currently set to {0}", sc.Status.ToString());

if (sc.Status == ServiceControllerStatus.Stopped)
{
    // Start the service if the current status is stopped.
    
Console.WriteLine("Starting the Alerter service...");
try
{
// Start the service, and wait until its status is "Running".
    sc.Start();
    sc.WaitForStatus(ServiceControllerStatus.Running);

    // Display the current service status.
    Console.WriteLine("The Alerter service status is now set to {0}.", sc.Status.ToString());
 }
 catch (InvalidOperationException)
 {
     Console.WriteLine("Could not start the Alerter service.");
 }
}
  1. You have to open your .exe application using right click > admin privilegies, but the better way is to add a manifest file so when the application open will ask for admin privilegies. you can check how to do that here: How to request administrator permissions when the program starts?
like image 55
Rafael Alfredo Zelaya Amaya Avatar answered Sep 07 '25 23:09

Rafael Alfredo Zelaya Amaya