<summary>
Start the service
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void Button1_Click (object sender, EventArgs e)
{
ServiceController sc = new ServiceController ("WindowsService1");
if (SC. Status.equals (servicecontrollerstatus.stopped))
{
Sc. Start ();
}
}
<summary>
Stop Service
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void Button2_Click (object sender, EventArgs e)
{
ServiceController sc = new ServiceController ("MSSQLSERVER");
if (!SC. Status.equals (servicecontrollerstatus.stopped))
{
Sc. Stop ();
}
}
<summary>
Installation Services
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void Button3_Click (object sender, EventArgs e)
{
if (!isserviceisexisted ("Service1"))
{
String location = System.Reflection.Assembly. GetExecutingAssembly (). Location;
String servicefilename = location. Substring (0, location. LastIndexOf ('///') + 1) + "WindowsService1.exe";
Installmyservice (null, servicefilename);
}
Else
{
MessageBox.Show ("The system already has this service installed! ");
}
}
<summary>
Uninstall Service
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void Button4_Click (object sender, EventArgs e)
{
if (isserviceisexisted ("Service1"))
{
String location = System.Reflection.Assembly. GetExecutingAssembly (). Location;
String servicefilename = location. Substring (0, location. LastIndexOf ('///') + 1) + "WindowsService1.exe";
Uninstallmyservice (Servicefilename);
}
Else
{
MessageBox.Show ("System does not exist for this service, do not need to uninstall!") ");
}
}
<summary>
Checking the existence of a service
</summary>
<param name= "Nameservice" > Service name </param>
<returns> presence returns True, otherwise returns false;</returns>
public static bool Isserviceisexisted (string nameservice)
{
servicecontroller[] Services = servicecontroller.getservices ();
foreach (ServiceController s in services)
{
if (s.servicename.tolower () = = Nameservice.tolower ())
{
return true;
}
}
return false;
}
<summary>
Installing Windows Services
</summary>
<param name= "Statesaver" > Collection </param>
<param name= "filepath" > program file path </param>
public static void Installmyservice (IDictionary statesaver, string filepath)
{
Assemblyinstaller AssemblyInstaller1 = new Assemblyinstaller ();
Assemblyinstaller1.usenewcontext = true;
Assemblyinstaller1.path = filepath;
Assemblyinstaller1.install (statesaver);
Assemblyinstaller1.commit (statesaver);
Assemblyinstaller1.dispose ();
}
<summary>
Uninstalling Windows Services
</summary>
<param name= "filepath" > program file path </param>
public static void Uninstallmyservice (string filepath)
{
Assemblyinstaller AssemblyInstaller1 = new Assemblyinstaller ();
Assemblyinstaller1.usenewcontext = true;
Assemblyinstaller1.path = filepath;
Assemblyinstaller1.uninstall (NULL);
Assemblyinstaller1.dispose ();
}
Install, uninstall, start, and close services in C # code