关于WIndows服务的介绍,之前写过一篇:
http://blog.csdn.net/yysyangyangyangshan/article/details/7295739。可能这里对如何写一个服务不是很详细。现在纯用代码的形式介绍一下windows服务是如何开发和安装的。
开发环境:Win7 32位;工具:visualstudio2010。
因为win7自带的就有.net环境,算是偷一下懒吧。因为无论是手动安装或程序安装都要用到。一个目录(默认C盘为操作系统的情况):C:\Windows\Microsoft.NET\Framework,如果你的代码是.net2.0:C:\Windows\Microsoft.NET\Framework\v2.0.50727;4.0:C:\Windows\Microsoft.NET\Framework\v4.0.30319。
下面看一下代码:
一、创建windows服务
如图新建一个Windows服务
进入程序如图
空白服务如下
只要在OnStart里完成你的功能代码即可。本例中我们做一个定时向本地文件写记录的功能。
如图
创建一个类,用户写文件,
那么在Service1中调用,
这样服务算是写的差不多了,下面添加一个安装类,用于安装。
如图,在service1上右键-添加安装程序,
如图,添加一个安装程序,
如图,添加完成后,
设置相应的属性,给serviceInstaller1设置属性,主要是描述信息。如图,
给serviceProcessInstaller1设置,主要是account。一般选localsystem,如图,
这样服务已经写好了。那么如何添加到windows服务里面去呢。除了之前说过的用CMD,InstallUtil.exe和服务的exe文件进行手动添加。这些可以用代码来实现的。当然主要过程都是一样的。代码实现也是使用dos命令来完成的。
二、代码安装Windows服务
上面写好的服务,最终生成的是一个exe文件。如图,
安装程序安装时需要用到这个exe的路径,所以方便起见,将这个生成的exe文件拷贝至安装程序的运行目录下。
再在安装目录下看记录的文件,
开发环境:Win7 32位;工具:visualstudio2010。
因为win7自带的就有.net环境,算是偷一下懒吧。因为无论是手动安装或程序安装都要用到。一个目录(默认C盘为操作系统的情况):C:\Windows\Microsoft.NET\Framework,如果你的代码是.net2.0:C:\Windows\Microsoft.NET\Framework\v2.0.50727;4.0:C:\Windows\Microsoft.NET\Framework\v4.0.30319。
下面看一下代码:
一、创建windows服务
如图新建一个Windows服务
进入程序如图
空白服务如下
只要在OnStart里完成你的功能代码即可。本例中我们做一个定时向本地文件写记录的功能。
如图
创建一个类,用户写文件,
那么在Service1中调用,
这样服务算是写的差不多了,下面添加一个安装类,用于安装。
如图,在service1上右键-添加安装程序,
如图,添加一个安装程序,
如图,添加完成后,
设置相应的属性,给serviceInstaller1设置属性,主要是描述信息。如图,
给serviceProcessInstaller1设置,主要是account。一般选localsystem,如图,
这样服务已经写好了。那么如何添加到windows服务里面去呢。除了之前说过的用CMD,InstallUtil.exe和服务的exe文件进行手动添加。这些可以用代码来实现的。当然主要过程都是一样的。代码实现也是使用dos命令来完成的。
二、代码安装Windows服务
上面写好的服务,最终生成的是一个exe文件。如图,
安装程序安装时需要用到这个exe的路径,所以方便起见,将这个生成的exe文件拷贝至安装程序的运行目录下。
安装代码,
这段代码其实可以放在项目中的某个地方,或单独执行程序中,只好设置好dotNetPath和serviceEXEPath路径就可以了。 运行完后,如图,再在安装目录下看记录的文件,
这样,一个windows服务安装成功了。
代码下载:http://download.csdn.net/detail/yysyangyangyangshan/6032671