C#创建Windows服务
来源:互联网 发布:iphone用淘宝发烫 编辑:程序博客网 时间:2024/05/01 04:05
1.打开VS程序,创建一个项目选择 Windows 服务,默认有一人 Service1.cs 类,在这里改名为 IndexService.cs 代码如下.
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace FileIndexService
...{
public partial class IndexService : ServiceBase
...{
public IndexService()
...{
InitializeComponent();
}
protected override void OnStart(string[] args)
...{
// TODO: 在此处添加代码以启动服务。
using (StreamWriter sws = new StreamWriter(@"D:Selfinservice.txt"))
...{
sws.Write("服务测试开始");
sws.Flush();
sws.Close();
}
}
protected override void OnStop()
...{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
using (StreamWriter sws = new StreamWriter(@"D:Selfinservice.txt"))
...{
sws.Write("服务测试结束");
sws.Flush();
sws.Close();
}
}
}
}
这里只是简单的读写文件操作.要处理的逻辑大家可以根据自己的需求来写代码.
2.创建一个ProjectInstall.cs类,要继承 Installer 类.代码如下:其中using System.Configuration.Install;句在System.Configuration.Install里,需要手动添加引用.
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.ServiceProcess;
using System.ComponentModel;
using System.Configuration.Install;
namespace FileIndexService
...{
[RunInstaller(true)]
public class ProjectInstall:Installer
...{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public ProjectInstall()
...{
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem; //这样,不论哪个用户登录的系统,服务总会启动
//Automatic 每次计算机重新启动时,服务都会自动启动
//Manual 服务安装后,必须手动启动
//Disabled 服务无法启动
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = "FileIndexService"; //设置服务的名称
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
}
如果不增加ProjectInstall.cs,则会报如下错误
没有 RunInstallerAttribute 的公共安装程序。在 f:/Self/TestCpuDemo/FileIndexService/bin/Debug/IndexService.exe 程序集中可能可以找到“Yes”属性。
大家可以先不添加试试看.
以下是摘自网络:
其中各属性的含意是:
ü Autolog 是否自动写入系统的日志文件
ü CanHandlePowerEvent 服务时候接受电源事件
ü CanPauseAndContinue 服务是否接受暂停或继续运行的请求
ü CanShutdown 服务是否在运行它的计算机关闭时收到通知,以便能够调用 OnShutDown 过程
ü CanStop 服务是否接受停止运行的请求
ü ServiceName 服务名
安装服务:
installutil FileIndexService.exe
卸载服务:
installutil /u FileIndexService.exe
- C#创建Windows服务
- C#创建Windows服务
- C# 创建 Windows 服务
- C# 创建windows服务
- C#创建Windows服务
- C# 创建windows服务
- c#创建windows服务
- C#创建Windows服务
- C# 创建Windows服务
- C#创建Windows服务
- C#创建windows服务
- C#创建windows服务
- C# 创建Windows Service服务 Windows服务
- C# 创建Windows 服务程序
- C# 创建Windows(NT)服务
- 用C#创建windows服务
- C#创建Windows服务程序
- c#创建Windows系统服务
- 写个餐厅发票生成系统
- 30岁前不必在意的事情(转)
- linux下mysql的一点基本用法
- Access 和 SQL Server数据类型的比较
- “软件工业奥斯卡”SYS-CON 读者选择奖: Java开发
- C#创建Windows服务
- 注意那些容易被忽略的SQL注入技巧
- sql分段处理删除大量数据
- ogre游戏制作一(安装和编译demo)
- 利用VC向EXCEL中写数据(转别人的)
- AOP是什么?
- 什么是SQL注入法攻击
- MySQL服务器内部安全数据目录访问
- 《程序员修炼之道》阅读记录 (1)