Code
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 ));
}
}
}
}
}