Gaurav Pal

Gaurav Pal

  • NA
  • 306
  • 69.1k

How to start Sql server Service

Dec 30 2015 3:13 AM
How to start all stop Sql Server Service using C#.net.
I am using below code but not working.
 
1.
 
private void ReStartService()
{
string strService = "MSSQL$SQLEXPRESS";
ServiceController serv = new ServiceController(strService);
if (serv != null)
{
serv.Stop();
serv.WaitForStatus(ServiceControllerStatus.Stopped);
serv.Start();
serv.WaitForStatus(ServiceControllerStatus.Running);
}
}
 
 
 
2.
 
public string RestartService(string serviceName, int timeoutMilliseconds)
{
string status= string.Empty;
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
//service.Stop();
//service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
status = service.Status.ToString();
}
catch (Exception ex)
{
status = ex.Message;
}
return status;
}
 

Answers (2)