.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

using System; using System.Diagnostics; using System.ServiceProcess; namespace MyService { partial class MySVC : ServiceBase { public MySVC() { this.ServiceName = "myservice"; this.CanStop = true; this.CanShutdown = true; this.CanPauseAndContinue = true; this.AutoLog = true; } protected override void OnStart(string[] args) { base.OnStart(args); EventLog.WriteEntry("MySVC.OnStart", "服务启动"); } protected override void OnStop() { base.OnStop(); } } }

 

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

using System; using System.Configuration.Install; using System.ServiceProcess; using System.ComponentModel; namespace MyService { [RunInstaller(true)] public partial class MyInstaller : Installer { private ServiceInstaller sInstall; private ServiceProcessInstaller sProcessInstall; public MyInstaller() { sInstall = new ServiceInstaller(); sProcessInstall = new ServiceProcessInstaller(); sProcessInstall.Account = ServiceAccount.LocalSystem; sInstall.StartType = ServiceStartMode.Automatic; sInstall.ServiceName = "myservice"; //这个服务名必须和步骤1中的服务名相同。 sInstall.DisplayName = "我服务"; sInstall.Description = "我服务。该服务的描述。"; Installers.Add(sInstall); Installers.Add(sProcessInstall); } } }

 

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

using System.ServiceProcess; namespace myService { static class Program { ///

/// 应用程序的主入口点。 /// static void Main() { ServiceBase[] ServicesToRun; // 同一进程中可以运行多个用户服务。若要将 // 另一个服务添加到此进程中,请更改下行以 // 创建另一个服务对象。例如, // // ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()}; // ServicesToRun = new ServiceBase[] { new MySVC() }; ServiceBase.Run(ServicesToRun); } } }

 

最后是安装该服务:

找到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的服务了。

你可能感兴趣的:(.NET)