This article mainly records learning. NET How to create a Windows service.
1. Create a Windows service program
2. Create a New installation program
3. Modify the service file
The code is as follows
protected Override voidOnStart (string[] args) { using(System.IO.StreamWriter SW =NewSystem.IO.StreamWriter ("C:\\log.txt",true) ) {SW. WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +"Start."); } } protected Override voidOnStop () {using(System.IO.StreamWriter SW =NewSystem.IO.StreamWriter ("C:\\log.txt",true) ) {SW. WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +"Stop."); } }
4. Using Installutil.exe to install the service
To open cmd with a tube machine operator
Execute command in switch to Bin directory
%systemroot%\microsoft.net\framework\v4. 0.30319\installutil.exe WindowsService2.exe
Note: Here to adjust the permissions of the installer:
5. Start the service
At this point in the C drive to generate a Log.txt file content as follows:
Stop the service and add the following in the Log.txt file
Add:
For more convenient installation and uninstallation of the service, two scripts were written. (both need to be performed with administrator privileges)
(1) Installation script
Set projectroot=D:\document\work\demo\windowServiceDemo\WindowsService2\bin\Debugcmd/k%systemroot%\ Microsoft.net\framework\v4. 0.30319\installutil.exe%projectroot%/windowsservice2.exe
(2) Uninstall script
Set projectroot=D:\document\work\demo\windowServiceDemo\WindowsService2\bin\Debugcmd/k%systemroot%\ Microsoft.net\framework\v4. 0.30319\installutil.exe/u%projectroot%/windowsservice2.exe
. NET create a Windows service get started