1. Install the service:
Private void installservice (idictionary statesaver, string filepath)
{
Try
{
System. serviceprocess. servicecontroller service = new system. serviceprocess. servicecontroller ("servicename ");
If (! Serviceisexisted ("servicename "))
{
// Install Service
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller ();
MyAssemblyInstaller. UseNewContext = true;
MyAssemblyInstaller. Path = filepath;
MyAssemblyInstaller. Install (stateSaver );
MyAssemblyInstaller. Commit (stateSaver );
MyAssemblyInstaller. Dispose ();
// -- Start Service
Service. Start ();
}
Else
{
If (service. Status! = System. ServiceProcess. ServiceControllerStatus. Running & service. Status! = System. ServiceProcess. ServiceControllerStatus. StartPending)
{
Service. Start ();
}
}
}
Catch (Exception ex)
{
Throw new Exception ("installServiceError/n" + ex. Message );
}
}
Ii. Uninstall the windows Service:
Private void UnInstallService (string filepath)
{
Try
{
If (ServiceIsExisted ("ServiceName "))
{
// UnInstall Service
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller ();
MyAssemblyInstaller. UseNewContext = true;
MyAssemblyInstaller. Path = filepath;
MyAssemblyInstaller. Uninstall (null );
MyAssemblyInstaller. Dispose ();
}
}
Catch (Exception ex)
{
Throw new Exception ("unInstallServiceError/n" + ex. Message );
}
}
3. Determine whether the window service exists:
Private bool ServiceIsExisted (string serviceName)
{
ServiceController [] services = ServiceController. GetServices ();
Foreach (ServiceController s in services)
{
If (s. ServiceName = serviceName)
{
Return true;
}
}
Return false;
}
4. Start the service:
Private void StartService (string serviceName)
{
If (ServiceIsExisted (serviceName ))
{
System. ServiceProcess. ServiceController service = new System. ServiceProcess. ServiceController (serviceName );
If (service. Status! = System. ServiceProcess. ServiceControllerStatus. Running & service. Status! = System. ServiceProcess. ServiceControllerStatus. StartPending)
{
Service. Start ();
For (int I = 0; I <60; I ++)
{
Service. Refresh ();
System. Threading. Thread. Sleep (1000 );
If (service. Status = System. ServiceProcess. ServiceControllerStatus. Running)
{
Break;
}
If (I = 59)
{
Throw new exception (startserviceerror. Replace ("$ S $", servicename ));
}
}
}
}
}
5. Stop the service:
Private void StopService (string serviceName)
{
If (ServiceIsExisted (serviceName ))
{
System. ServiceProcess. ServiceController service = new System. ServiceProcess. ServiceController (serviceName );
If (service. Status = System. ServiceProcess. ServiceControllerStatus. Running)
{
Service. Stop ();
For (int I = 0; I <60; I ++)
{
Service. Refresh ();
System. Threading. thread. Sleep (1000 );
If (service. Status = system. serviceprocess. servicecontrollerstatus. Stopped)
{
Break;
}
If (I = 59)
{
Throw new Exception (stopServiceError. Replace ("$ s $", serviceName ));
}
}
}
}
}