C # Create a service and use the program to install the service automatically. NET to create an EXE that is an executable program and a Windows service

Source: Internet
Author: User

Have to say that. NET installation service is very troublesome, that is, to create a service, create a serviceinstall, and finally get a bunch of commands to install and uninstall.

Today gives you a way to use our program directly to install/uninstall the service, and allows an EXE to run directly or install as a Windows service


First we create a Windows application, (I create a console program, WinForm is the same)

Next, add a Windows service class to your project

Then double-click "MainService.cs" and right-click on the "Open Code" button.

Here is the specific implementation of the service, the following is the sample code I wrote

Partial class Mainservice:servicebase    {public        mainservice ()        {            InitializeComponent ();        }        protected override void OnStart (string[] args)        {            //TODO:  Add code here to start the service.            System.IO.File.AppendAllText ("D:\\log.txt", "service started ..." + DateTime.Now.ToString ());        protected override void OnStop ()        {            ///TODO:  Add code here to perform the close operation required to stop the service.            System.IO.File.AppendAllText ("D:\\log.txt", "Service stopped ..." + DateTime.Now.ToString ());}    

Then we change the program portal to the main method to identify whether it is a Windows application or a Windows service at startup, and if the application executes code for the application, execute the Mainservice code if it is a service

If it is a service, I give an "s" parameter, if there is this parameter proves to be the Windows service, then start Mainservice

static void Main (string[] args)        {           //If the ' s ' parameter is passed, start the service if            (args. Length > 0 && args[0] = = "S")            {               //Start service code, can copy                servicebase[] ServicesToRun from other places;                ServicesToRun = new servicebase[]                 {                     new Mainservice (),                };                Servicebase.run (ServicesToRun);            }            else            {}

Then, we implement the function of the application, that is, the Else statement block above, the function of the application is to install/uninstall the service, can be installed and uninstalled with Windows's own SC command, the specific code is as follows:

                Console.WriteLine ("This is the Windows Application");                Console.WriteLine ("Please select, [1] Install the service [2] Uninstall service [3] exit");                var rs = Int. Parse (Console.ReadLine ());                Switch (RS)                {case                    1:                        //Take the current executable path, plus the "s" parameter, which proves to be starting the program from Windows service                        var path = process.getcurrentprocess ( ). Mainmodule.filename + "s";                        Process.Start ("SC", "Create MyServer binpath= \" "+ Path +" \ "displayname= my service start= auto");                        Console.WriteLine ("Successful Installation");                        Console.read ();                        break;                    Case 2:                        process.start ("SC", "delete myserver");                        Console.WriteLine ("Uninstall succeeded");                        Console.read ();                        break;                    Case 3:break;                }

So we can implement an application that is the executable program and the Windows service.

The complete code for the main method is as follows

 static void Main (string[] args) {if (args.                Length > 0 && args[0] = = "S") {servicebase[] servicestorun;                ServicesToRun = new servicebase[] {new Mainservice (),};            Servicebase.run (ServicesToRun);                } else {Console.WriteLine ("This is a Windows application");                Console.WriteLine ("Please select, [1] Install the service [2] Uninstall service [3] exit"); var rs = Int.                Parse (Console.ReadLine ());                        Switch (RS) {Case 1://Take the current executable path, plus the "s" parameter, which proves to be starting the program from the Windows service var path = process.getcurrentprocess ().                        Mainmodule.filename + "S";                        Process.Start ("SC", "Create MyServer binpath= \" "+ Path +" \ "displayname= my service start= auto");                        Console.WriteLine ("Successful Installation");                        Console.read (); BreAk                        Case 2:process.start ("SC", "delete myserver");                        Console.WriteLine ("Uninstall succeeded");                        Console.read ();                    Break                Case 3:break; }            }        }

At this point, the program has been basically finished, and then we test

Directly double-click ServiceOrApp.exe

Input 1

Prompt for installation to succeed, then run "services.msc" to open Service Manager

You can see that our service has been successfully installed, then right-click to start the service

Successfully started

Then go to D-disk and see Log.txt.

Indicates that the service is performing properly

We'll stop the service.

After the successful stop, look at the D-Disk Log.txt file.

See above, the service start and stop all right (forget to output line break--!) )

Then let's try the uninstall service again, or double-click ServiceOrApp.exe, select 2

Prompt for uninstallation to succeed, and then run "services.msc" to open Service Manager

Can see there is no "my service", has been successfully uninstalled

Install and uninstall here the main use of the Windows SC command, and then use the startup parameters to determine whether it is a service or program to execute different code

C # Create a service and use the program to install the service automatically. NET to create an EXE that is an executable program and a Windows service

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.