.NET self-registering Windows Service

I just found an article about how to extend a windows service’s functionality so that the service can register itself in windows service control using command line switches like /register or /unregister.. Logo_Microsoft_VisualStudio_2010

 
using System.Configuration.Install;
using System.Linq;
using System.Windows.Forms;
namespace MyService
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Any(item => item == "/install"))
            {
                ServiceSelfInstaller.Install();
            }
            else if
                (args.Any(item => item == "/uninstall"))
                ServiceSelfInstaller.Uninstall();
            else
            {
                //Run Service...            
            }
        }
        internal static class ServiceSelfInstaller
        {
            public static void Install()
            {
                ManagedInstallerClass.InstallHelper(new[] { Application.ExecutablePath });
            }
            public static void Uninstall()
            {
                ManagedInstallerClass.InstallHelper(new[] { "/u", Application.ExecutablePath });
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *