Saturday, September 19, 2009

Installing and Uninstalling Windows Service using C#

Install Windows Service:
public override void Install(System.Collections.IDictionary stateSaver)
        {
           
            base.Install(stateSaver);

            ConnectionOptions options = new ConnectionOptions();
            options.EnablePrivileges = true;
            options.Impersonation = ImpersonationLevel.Impersonate;

            ManagementScope scope = new ManagementScope(new ManagementPath(@"\ROOT\CIMV2"), options);
            scope.Connect();

            ManagementPath path = new ManagementPath("Win32_Service");

            ManagementClass mc = new ManagementClass(scope, path, new ObjectGetOptions());
            ManagementBaseObject inParams = mc.GetMethodParameters("create");

            inParams["Name"] = "GCSBLServices";
            inParams["DisplayName"] = "GCS BL Services";
            inParams["PathName"] = Context.Parameters["name"].ToString() + "BL.WndService.exe";
            inParams["StartName"] = @".\LocalSystem";
            inParams["StartPassword"] = "";

            ManagementBaseObject outParams = mc.InvokeMethod("create", inParams, null);

            ManagementPath path1 = new ManagementPath(string.Format("Win32_Service.Name='{0}'", "GCSBLServices"));

            using (ManagementObject service = new ManagementObject(scope, path1, new ObjectGetOptions()))
            {
               
                ManagementBaseObject outParams1 = service.InvokeMethod("StartService", null, null);
                   
            }
        }


Uninstall Windows Service:
public override void Uninstall(System.Collections.IDictionary savedState)
        {
            base.Uninstall(savedState);
            ConnectionOptions options = new ConnectionOptions();
            options.EnablePrivileges = true;
            options.Impersonation = ImpersonationLevel.Impersonate;

            ManagementScope scope = new ManagementScope(new ManagementPath(@"\ROOT\CIMV2"), options);
            scope.Connect();

            ManagementPath path = new ManagementPath(string.Format("Win32_Service.Name='{0}'", "GCSBLServices"));

            using (ManagementObject service = new ManagementObject(scope, path, new ObjectGetOptions()))
            {
               ManagementBaseObject outParams = service.InvokeMethod("StopService", null, null);
            }
           
            using (ManagementObject service = new ManagementObject(scope, path, new ObjectGetOptions()))
            {
                 ManagementBaseObject outParams = service.InvokeMethod("delete", null, null);   
            }
        }




No comments:

Post a Comment