I have the following code of a console application in C# to start the SQLSERVER 2016 service, but I have not been able to, here is the code and the code error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string myServiceName = "MSSQL$SQLEXPRESS"; //service name of SQL Server Express
string status; //service status (For example, Running or Stopped)
Console.WriteLine("Service: " + myServiceName);
//display service status: For example, Running, Stopped, or Paused
ServiceController mySC = new ServiceController(myServiceName);
try
{
status = mySC.Status.ToString();
}
catch (Exception ex)
{
Console.WriteLine("Service not found. It is probably not installed. [exception=" + ex.Message + "]");
Console.ReadLine();
return;
}
//display service status: For example, Running, Stopped, or Paused
Console.WriteLine("Service status : " + status);
//if service is Stopped or StopPending, you can run it with the following code.
if (mySC.Status.Equals(ServiceControllerStatus.Stopped) | mySC.Status.Equals(ServiceControllerStatus.StopPending))
{
try
{
Console.WriteLine("Starting the service...");
mySC.Start();
mySC.WaitForStatus(ServiceControllerStatus.Running);
Console.WriteLine("The service is now " + mySC.Status.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Error in starting the service: " + ex.Message);
}
}
Console.WriteLine("Press a key to end the application...");
Console.ReadLine();
return;
}
}
}
and here is the result of the application.
Do you have any idea why I can't start that service? Thanks in advance
It was all about permissions, I had to add a manifest file in my application to run it as Administrator, I leave you some images so you can see it.
And I had to change this line
now the application does not throw an exception if the SQL service is stopped.
It may be a permissions error, since to run the SQL service your application must be running with elevation and as an administrator, you can test it by running the following command from the Windows command prompt:
If the result is " Access Denied ", it is due to permissions, in this case compile your application and try running the EXE as administrator and it should work (right click "Run as administrator").
It may also be that the name of your instance is not correct, in which case the first command will send you a result like this:
You can query the name of your SQL instance using the following command: