.net服务安装(转载)

通常要开发一个.NET服务要以下步骤:

1. 新建一个继承自 System.ServiceProcess.ServiceBase的类,并根据需要重写该类OnStart,OnStop,OnShutdown等方法。一般OnStart方法肯定要重写,要不然服务没意思。

2. 新建一个继承自 System.Configuration.Install.Installer 类的安装类。该类定义了要安装的服务的一些基本信息,如服务名,服务的运行方式等。

3. 写一个包含Main方法的类,在Main中运行服务,方法是调用ServiceBase中的Run方法。

4. 最后要安装服务的话要用.NET Framework提供的 InstallUtil.exe 工具来安装。

代码如下:

首先是步骤1中的类,MySVC.cs

然后是步骤2的类,MyInstaller.cs

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Configuration.Install;  
  3. using System.ServiceProcess;  
  4. using System.ComponentModel;  
  5. namespace MyService  
  6. {  
  7.     [RunInstaller(true)]  
  8.     public partial class MyInstaller : Installer  
  9.     {  
  10.         private ServiceInstaller sInstall;  
  11.         private ServiceProcessInstaller sProcessInstall;  
  12.         public MyInstaller()  
  13.         {  
  14.             sInstall = new ServiceInstaller();  
  15.             sProcessInstall = new ServiceProcessInstaller();  
  16.             sProcessInstall.Account = ServiceAccount.LocalSystem;  
  17.             sInstall.StartType = ServiceStartMode.Automatic;  
  18.             sInstall.ServiceName = "myservice"//这个服务名必须和步骤1中的服务名相同。  
  19.             sInstall.DisplayName = "我服务";  
  20.             sInstall.Description = "我服务。该服务的描述。";  
  21.             Installers.Add(sInstall);  
  22.             Installers.Add(sProcessInstall);  
  23.         }  
  24.     }  
  25. }  

再然后是一个控制台类,Program.cs

[c-sharp] view plaincopy
  1. using System.ServiceProcess;  
  2. namespace myService  
  3. {  
  4.     static class Program  
  5.     {  
  6.         /// <summary>  
  7.         /// 应用程序的主入口点。  
  8.         /// </summary>  
  9.         static void Main()  
  10.         {  
  11.             ServiceBase[] ServicesToRun;  
  12.             // 同一进程中可以运行多个用户服务。若要将  
  13.             // 另一个服务添加到此进程中,请更改下行以  
  14.             // 创建另一个服务对象。例如,  
  15.             //  
  16.             //   ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};  
  17.             //  
  18.             ServicesToRun = new ServiceBase[] { new MySVC() };  
  19.             ServiceBase.Run(ServicesToRun);  
  20.         }  
  21.     }  
  22. }  

最后是安装该服务:

找到InstallUtil.exe的位置,默认在C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727 目录下,如果你安装的是XP系统的话。 把当前目录转到步骤3中控制台生成的exe文件的目录中。运行 C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/InstallUtil.exe  myService.exe

你可以打开“服务”看看是不是我了一个叫做myservice的服务了。

原文地址:https://www.cnblogs.com/zhwl/p/2418228.html