您的位置:首页 > 编程语言 > C#

C# 创建Windows 服务程序

2010-01-12 16:23 676 查看
Windows服务是一种无界面的程序..运行在计算机后台..用于执行一些不需要GUI界面的功能...

Windows服务特点: 可以随机启动 不在进程内 无界面 如果功能满足这些 可以用Windows服务

第一步:创建Windows服务程序

第二步:添加安装程序

选择Service1 -> 右键->安装程序

选择serviceProcessInstaller1组件 属性->Account为LocalSystem //意思为本地服务.

选择serviceInstaller1组件属性->

Description 描述

DisplayName 显示友好名称

ServiceName 系统服务名称

StartType 启动方式 Automatic 为自动随机启动

第三步:编写代码

using System;
using System.Timers;//由于不能使用Window Froms timer控件 所以引用这个时间控件实现每秒执行一次
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using XiangleSystem;
namespace winservice
{
/// <summary>
/// 功能:启动停止写文件 期间每秒执行一次写文件
/// </summary>
public partial class Service1 : ServiceBase
{
private FileSystem file = new FileSystem();//文件操作业务层
Timer timer = new Timer();//创建时间控件
public Service1()
{
InitializeComponent();
timer.Interval = 1000;//设置时间间隔
timer.Enabled = true;//开启
timer.Elapsed+=new ElapsedEventHandler(timer_Elapsed);//加载事件
}

protected void timer_Elapsed(object sender, ElapsedEventArgs e)
{
file.WriteFile(DateTime.Now.ToString(), "c://service.txt");//每秒加一个时间
}

protected override void OnStart(string[] args)
{
// TODO: 在此处添加代码以启动服务。
//启动服务的时候写入启动在c:/1.txt
file.WriteFile("启动","c://service.txt");
}

protected override void OnStop()
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
//停止服务的时候写入启动在c:/1.txt
file.WriteFile("停止", "c://service.txt");
}

}
}


第四步:安装Windows服务和卸载Windows服务

第一种方法:利用 Microsoft Visual Studio 2005 x86 tools

打开Microsoft Visual Studio 2005 x86 tools

安装服务命令:

installutil E:/Chat/windows_service/YuanBo.WebChat.NTService.exe(exe文件路径)

反安装服务命令

installutil /u E:/Chat/windows_service/YuanBo.WebChat.NTService.exe(exe文件路径)

第二种方法:C#编程实现安装和卸载

详见:http://blog.csdn.net/lhypang2006/archive/2010/01/12/5180840.aspx

第三种:dos 实现安装和卸载

//安装服务 注意"="号后面必须有一空格否则出错
sc create mys binpath= "c:/winservice.exe" displayname= "测试服务" start= auto

//删除服务
sc delete mys

//修改服务
sc config mys binpath= "c:/winservice.exe" displayname= "Svnservice"

设置为自启动
sc config mys start= auto

启动服务

net start Svnservice

期间出现错误解决:

windows服务程序,安装的过程中出现设置服务登陆的对话框!要求输入用户和密码!

解决方式:

选择Service1 -> 右键->安装程序

选择serviceProcessInstaller1组件 属性->Account为LocalSystem //意思为本地服务
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: