C # Windows Service (Windows services) related

Source: Internet
Author: User

Https://www.cnblogs.com/charlie-chen2016/p/8031774.html

This is a backup of the database service, the logic is very simple, is the implementation of the timer at a specific time to execute the SQL statement back up the database, and each step of the situation to write to the log file.

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Diagnostics;usingSystem.Linq;usingsystem.serviceprocess;usingSystem.Text;usingSystem.Data.SqlClient;namespacedatabaseservice{ Public Partial classdatabakservice:servicebase{ PublicDatabakservice () {InitializeComponent ();}//TimerSystem.Timers.Timer Tmbak =NewSystem.Timers.Timer ();//write Log on server startup, turn on timerprotected Override voidOnStart (string[] args) {using(System.IO.StreamWriter SW =NewSystem.IO.StreamWriter ("D:\\log.txt",true) ) {SW. WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +"DATABASENAME Service Start.");}//execution of events by TimeTmbak.interval=60000;//one-minute executionTmbak.autoreset =true;//executes false once, always executes true//whether to perform the System.Timers.Timer.Elapsed eventtmbak.enabled =true; Tmbak.start (); tmbak.elapsed+=NewSystem.Timers.ElapsedEventHandler (Sqlbak);}Private voidSqlbak (Objectsource, System.Timers.ElapsedEventArgs E) {//If the current time is 10:30if(DateTime.Now.Hour = =9&& DateTime.Now.Minute = = -){stringsql =string. Format (@"BACKUP DATABASE DATABASENAME to DISK = N ' E:\DBBak\DATABASENAME {0}{1}{2}.bak '--the directory must be present with INIT, nounload, NAME = N ' Database backup ',--name casually take noskip, STATS = ten, Noformat", datetime.now.year,datetime.now.month,datetime.now.day);Try{using(System.IO.StreamWriter SW =NewSystem.IO.StreamWriter ("D:\\log.txt",true) ) {SW. WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +"backing up databasename database ...");} SqlConnection Conn=NewSqlConnection ("Server=127.0.0.1;uid=sa;pwd=44545454;database=databasename"); Conn. Open (); SqlCommand cmd=NewSqlCommand (SQL, conn); Cmd.commandtimeout=0; cmd. ExecuteNonQuery (); Conn. Close ();}Catch(Exception ex) {using(System.IO.StreamWriter SW =NewSystem.IO.StreamWriter ("D:\\log.txt",true) ) {SW. WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +"An exception occurred while backing up the DatabaseName database:"+Ex. Message);return;}}using(System.IO.StreamWriter SW =NewSystem.IO.StreamWriter ("D:\\log.txt",true) ) {SW. WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +"backup DatabaseName Database successfully! ");}}}//Write log when service is stoppedprotected Override voidOnStop () {using(System.IO.StreamWriter SW =NewSystem.IO.StreamWriter ("D:\\log.txt",true) ) {SW. WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +"DATABASENAMEService Stop.");}}}}
View Code

Service command:

installation:%systemroot%\microsoft.net\framework\v4. 0.30319 \installutil.exe windowservice directory \windowservice.exenet start serviceefnetsyssc config Serviceefnetsys start = Auto unload:%systemroot%\microsoft.net\framework\v4. 0.30319\installutil.exe/u windowservice directory \windowservice.exe---If you need to see the script health, Add pause to the last line of the script
View Code

Installing the InstallUtil.exe tool

Open the cmd window to perform the separate
CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe Window service directory/windows service. exe

SC command
Open the cmd window to execute
SC Create service name binpath= "Windows Service item bin\release under the. exe file address" Start=auto there is a space behind binpath=

Uninstalling the InstallUtil.exe tool

CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe-u Window service directory/windows service. exe

sc command SC Delete Service name

******************************************************************************

The service name can be removed from the SC command or the registry

Command line Remove Windows System Services method one:

With Sc.exe this Windows command
Start-run--cmd.exe and enter SC to see it. The way to use it is simple:
SC Delete "service name" (if there is a space in the middle of the service name, it needs to be quoted before and after)
As for the above: SC delete ksd2service

Registry removal Windows System service method two:

Direct registry editing (not recommended)
Open Registry Editor and locate the following key value:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services General Service will show a key in the same name here, directly delete the relevant keys can be.

PS: Special case

1, if the service display is rundll32.exe, and this file is located in the System32 directory, then you can not delete this rundll32.exe file, it is the Windows system files. Then just clear the relevant services.

2, if a service deleted immediately and automatically established, indicating that there is a process in the background monitoring, protection. You need to kill the corresponding process in the Process Manager first, or press F8 after startup to remove it in safe mode.

C # Windows Service (Windows services) related

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.