C# console program registered as Windows service

Add a new item in the console program——>"Windows Service"

Change the name, I call it "Test_WindowsService"

Then press F7 to modify the code in the newly added "Windows Service"

Cut all the code in the original console entry into the OnStart() method, which will run when the service is started.

 

Then add the following code to the original console entry program:

        static void Main(string[] args)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Test_WindowsService() //这里的Test_WindowsService新增的Windows服务
			};
            ServiceBase.Run(ServicesToRun);
        }

 Then right-click on the new Windows service and add the installer

 There will be "serviceProcessInstaller1" and "serviceInstaller1" in the new installation program. Modify the Account attribute in serviceProcessInstaller1 to "LocalSystem" (system service level), and modify the name and description attributes in serviceInstaller1 according to your needs:

 

 Then right-click to generate it, then go to the "C:\Windows\Microsoft.NET\Framework\v4.0.30319" directory to find "Installutil.exe", copy this program to the Debug directory generated by the project, and in this directory Create and modify two txt files (setup.txt/unsetup.txt), one is "installutil This is your console program name.exe", the other is "installutil This is your console program name.exe /u ", and then modify the suffix of these two txt files to bat files. Double-click setup.bat to install the service. You can start your service in Windows Services. Double-click unsetup.bat to uninstall the service.

 If you encounter the following problems:

An exception occurred during the installation phase.
System.Security.SecurityException: Source not found, but unable to search some or all of the event log files. Inaccessible log files: Security, State.

Solution:

Search for cmd in the start program, then right-click, run as administrator, switch to the Debug directory, and then execute setup.bat to install successfully.

 

Guess you like

Origin blog.csdn.net/qq_51502150/article/details/127070146