Search code examples
c#.netwindowswindows-services

How can I enable or disable a windows service in .NET?


How can I enable or disable a windows service in .NET? What do I have to know: its name or some kind of its id? In particular, in Windows 10.


Solution

  • You can enable or disable it by its name like

    sc config <your_service_name> start= disabled
    

    However if you are looking for a programmatic way then you can try this:

        using (var m = new ManagementObject($"Win32_Service.Name=\"{serviceName}\""))
        {
            m.InvokeMethod("ChangeStartMode", new object[] { "Automatic" });
        }
    

    Please check ChangeStartMode method of the Win32_Service class