Using System;
Using System. Configuration. Install;
Using System. Collections;
Using System. Collections. Specialized;
IDictionary stateSaver = new Hashtable ();
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 );
}
}
Or
/// <Summary>
/// Install the service
/// </Summary>
/// <Param name = "p_Path"> specify the path of the service file </param>
/// <Param name = "p_ServiceName"> return the service name after installation </param>
/// <Returns> If the installation information is correct, "" </returns>
Public static string InsertService (string p_Path, ref string p_ServiceName)
{
If (! File. Exists (p_Path) return "the File does not exist! ";
P_ServiceName = "";
FileInfo _ InsertFile = new FileInfo (p_Path );
IDictionary _ SavedState = new Hashtable ();
Try
{
// Load an assembly and run all the installation programs.
AssemblyInstaller _ AssemblyInstaller = new AssemblyInstaller (p_Path, new string [] {"/LogFile =" + _ InsertFile. directoryName + "//" + _ InsertFile. name. substring (0, _ InsertFile. name. length-_ InsertFile. extension. length) + ". log "});
_ AssemblyInstaller. UseNewContext = true;
_ AssemblyInstaller. Install (_ SavedState );
_ AssemblyInstaller. Commit (_ SavedState );
Type [] _ TypeList = _ AssemblyInstaller. Assembly. GetTypes (); // gets the set of installation Assembly types
For (int I = 0; I! = _ TypeList. Length; I ++)
{
If (_ TypeList [I]. BaseType. FullName = "System. Configuration. Install. Installer ")
{
// Find the System. Configuration. Install. Installer type.
Object _ insertobject = system. activator. createinstance (_ typelist [I]); // create a real column of the type
Fieldinfo [] _ fieldlist = _ typelist [I]. getfields (bindingflags. nonpublic | bindingflags. instance );
For (INT z = 0; Z! = _ Fieldlist. length; Z ++)
{
If (_ fieldlist [Z]. fieldtype. fullname = "system. serviceprocess. serviceinstaller ")
{
Object _ serviceinsert = _ fieldlist [Z]. getvalue (_ insertobject );
If (_ serviceinsert! = NULL)
{
P_servicename = (serviceinstaller) _ serviceinsert). servicename;
Return "";
}
}
}
}
}
Return "";
}
Catch (exception ex)
{
Return 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 ));
}
}
}
}
}
Other methods
/// <Summary>
/// Start the service
/// </Summary>
/// <Param name = "serviceName"> </param>
/// <Returns> </returns>
Public static bool ServiceStart (string serviceName)
{
Try
{
Servicecontroller service = new servicecontroller (servicename );
If (service. Status = servicecontrollerstatus. Running)
{
Return true;
}
Else
{
TimeSpan timeout = TimeSpan. FromMilliseconds (1000*10 );
Service. Start ();
Service. WaitForStatus (ServiceControllerStatus. Running, timeout );
}
}
Catch
{
Return false;
}
Return true;
}
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 ));
}
}
}
}
}
Another method:
/// <Summary>
/// Stop the service
/// </Summary>
/// <Param name = "servisename"> </param>
/// <Returns> </returns>
Public static bool servicestop (string servisename)
{
Try
{
ServiceController service = new ServiceController (serviseName );
If (service. Status = ServiceControllerStatus. Stopped)
{
Return true;
}
Else
{
TimeSpan timeout = TimeSpan. FromMilliseconds (1000*10 );
Service. Stop ();
Service. WaitForStatus (ServiceControllerStatus. Running, timeout );
}
}
Catch
{
Return false;
}
Return true;
}
6. Modify the startup items of the service
/// <Summary>
/// Modify service startup Item 2 to automatic, and 3 to manual
/// </Summary>
/// <Param name = "startType"> </param>
/// <Param name = "serviceName"> </param>
/// <Returns> </returns>
Public static bool changeservicestarttype (INT starttype, string servicename)
{
Try
{
Registrykey regist = registry. localmachine;
Registrykey sysreg = regist. opensubkey ("system ");
Registrykey CurrentControlSet = sysreg. opensubkey ("CurrentControlSet ");
RegistryKey services = currentControlSet. OpenSubKey ("Services ");
RegistryKey servicesName = services. OpenSubKey (serviceName, true );
ServicesName. SetValue ("Start", startType );
}
Catch (Exception ex)
{
Return false;
}
Return true;
}
7. Obtain the Service Startup Type
/// <Summary>
/// Get Service Startup Type 2: automatic; 3: manual; 4: Disabled
/// </Summary>
/// <Param name = "servicename"> </param>
/// <Returns> </returns>
Public static string getservicestarttype (string servicename)
{
Try
{
RegistryKey regist = Registry. LocalMachine;
RegistryKey sysReg = regist. OpenSubKey ("SYSTEM ");
RegistryKey currentControlSet = sysReg. OpenSubKey ("CurrentControlSet ");
RegistryKey services = currentControlSet. OpenSubKey ("Services ");
RegistryKey servicesName = services. OpenSubKey (serviceName, true );
Return servicesName. GetValue ("Start"). ToString ();
}
Catch (Exception ex)
{
Return string. Empty;
}
}
8. Check whether the service has been started.
/// <Summary>
/// Verify whether the service is started
/// </Summary>
/// <Returns> </returns>
Public static bool ServiceIsRunning (string serviceName)
{
ServiceController service = new ServiceController (serviceName );
If (service. Status = ServiceControllerStatus. Running)
{
Return true;
}
Else
{
Return false;
}
}
/// <Summary>
/// Whether the service exists
/// </Summary>
/// <Param name = "serviceName"> </param>
/// <Returns> </returns>
Public static bool ServiceExist (string serviceName)
{
Try
{
String m_ServiceName = serviceName;
ServiceController [] services = ServiceController. GetServices ();
Foreach (ServiceController s in services)
{
If (s. ServiceName. ToLower () = m_ServiceName.ToLower ())
{
Return true;
}
}
Return false;
}
Catch (Exception ex)
{
Return false;
}
}
Note: To manually install the window service, follow these steps:
In the Visual Studio 2005 Command Prompt window, run:
Installation Service: installutil servicepath
Unload service: installutil/u servicepath