locked
How can I start or stop system service like MSSQLSERVER? RRS feed

  • Question

  • How can I start or stop system service like MSSQLSERVER?

    Normally I start system service in command line 'net start MSSQLSERVER'

    How can I start or stop a service with C#? Certainly before you start a service we should detect if the service have been started, how to detect in C#?

    Wednesday, July 27, 2005 5:56 AM

Answers

  • Hi Cui Wei,

    you can use:

    System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("MSSQLSERVER");
    sc.Start();
    sc.Stop();

    use:

    System.ServiceProcess.ServiceController scc[] = System.ServiceProcess.ServiceController.GetServices();

    to get an array of all local services.

    HTH,
    SvenC
    Wednesday, July 27, 2005 6:21 AM

All replies

  • Hi Cui Wei,

    you can use:

    System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("MSSQLSERVER");
    sc.Start();
    sc.Stop();

    use:

    System.ServiceProcess.ServiceController scc[] = System.ServiceProcess.ServiceController.GetServices();

    to get an array of all local services.

    HTH,
    SvenC
    Wednesday, July 27, 2005 6:21 AM
  • Thank you for this posting. I am looking to start/stop a service from an app. I added the code that you posted and am getting an error saying "The type or namespace name 'ServiceProcess' does not exist in the class or namespace 'System' (are you missing an assembly reference?)". I have not been able to find what I am missing. Could somebody please help?


    Tuesday, August 23, 2005 9:54 PM
  • Although ServiceProcess exists in .Net 2.0 i can't make it work either.. there is no Class named ServiceController in ServiceProcess namespace.

    Tuesday, August 23, 2005 9:57 PM
  • Ops sorry.
    ServiceController is there!

    eg

    System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("Service name");
    sc.Start();
    sc.Stop();

    You just have to add a reference to System.ServiceProcess.dll
    I did that, worked fine.

    Tuesday, August 23, 2005 10:15 PM
  • Excellent! That is what I was missing.

    Thank you.
    Wednesday, August 24, 2005 3:22 PM