ch8_16.cs

来自「《c#技术内幕代码》」· CS 代码 · 共 95 行

CS
95
字号
using System;
using System.ServiceProcess;

class CH8_16
{
     public static void StartService( string server, string service )
     {
        try
	{
           Console.WriteLine("About to start the {0} Service", service );
	   ServiceController svcCtrl;
	   
	   if ( server.Length != 0 )
	      svcCtrl = new ServiceController(server, service);
	   else
	      svcCtrl = new ServiceController(service);
	   
           svcCtrl.Start();
	}
        catch(Exception e)
	{
           Console.WriteLine("Cought exception of : {0}", e.ToString());
        }
     }
     
     public static void StopService( string server, string service )
     {
        try
	{
           Console.WriteLine("About to stop the {0} Service", service );
	   ServiceController svcCtrl;
	   
	   if ( server.Length != 0 )
	      svcCtrl = new ServiceController(server, service);
	   else
	      svcCtrl = new ServiceController(service);
	   
           svcCtrl.Stop();
	}
        catch(Exception e)
	{
           Console.WriteLine("Cought exception of : {0}", e.ToString());
        }
     }

     public static void ShowServices( string server )
     {
        try
	{
	   ServiceController[] services;
	   if ( server.Length != 0 )
              services = ServiceController.GetServices(server);
	   else
	      services = ServiceController.GetServices();
	      
           foreach ( ServiceController svc in services)
	   {
               Console.WriteLine("Found service : {0}", svc.DisplayName); 
           }
	}
        catch(Exception e)
	{
           Console.WriteLine("Cought exception of : {0}", e.ToString());
        }
     }
     
     
     public static int Main(string[] args)
     {
         if(args.Length == 0)
         {
             Console.WriteLine("Syntax: service <server> <command> [service_name]");
             return -1;
         }
	 
         if ( args[1] == "Start" )
	 {
	    StartService( args[0], args[2] );
	 }
	 
         if ( args[1] == "Stop" )
	 {
	    StopService( args[0], args[2] );
	 }

	 if ( args[1] == "Show" )
	 {
	    ShowServices( args[0] );
	 }
	 
         return 0;
     }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?