VS 2010一步步开发windows服务(windows service)
基于0起步来创建一个服务,做到简单的记录时间日志功能,其具体招行方法可自行添加。
1.创建服务
2.删除默认服务文件
3.添加自己的服务文件
4.更改启动项目
5. 引用 using System.Timers;并添加FileClass类
FileClass类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; namespace TerminalTrance
{
public class FileClass
{
//创建文件夹
//参数:path 文件夹路径
public bool CreateFolder(string path)
{
try
{
if (Directory.Exists(path))
{
return true;
}
if (!Directory.Exists(path.Substring(, path.LastIndexOf("\\"))))
{ //若路径中无“\”则表示路径错误
return false;
}
else
{
//创建文件夹
DirectoryInfo dirInfo = Directory.CreateDirectory(path);
return true;
}
}
catch (Exception ex)
{
return false;
}
} //创建文件
//参数:path 文件路径
public void CreateFile(string path)
{
try
{
if (CreateFolder(path.Substring(, path.LastIndexOf("\\"))))
{
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
}
}
catch (Exception ex)
{
return;
} } //删除文件
//参数:path 文件夹路径
public void DeleteFile(string path)
{
try
{
if (!File.Exists(path))
{
return;
}
else
{
File.Delete(path);
} }
catch (Exception ex)
{
return;
}
} //写文件
//参数:path 文件夹路径 、content要写的内容
public void WriteFile(string path, string content)
{
try
{
if (!File.Exists(path))
{
CreateFile(path);
}
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(content);
sw.Close();
}
catch (Exception ex)
{
return;
}
} /// <summary>
/// 将即时日志保存入日志文件
/// </summary>
public void WriteLogFile(string directoryPath, string content)
{
if (!Directory.Exists(directoryPath))
{
CreateFolder(directoryPath);
}
try
{
//写入新的文件
string filePath = directoryPath + "\\" + DateTime.Now.Date.ToString("yyyyMMdd") + ".log";
FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(content);
sw.Close();
fs.Close();
}
catch (Exception ex)
{ } }
} }
6. 添加上步中需要的InitService()方法
/// <summary>
/// 初始化服务参数
/// </summary>
private void InitService()
{
base.CanShutdown = true;
base.CanStop = true;
base.CanPauseAndContinue = true;
this.ServiceName = MainService.serviceName;
this.AutoLog = false;//为了使用自定义日志,必须将 AutoLog 设置为 false tim = new System.Timers.Timer();
tim.Elapsed += new ElapsedEventHandler(tim_Elapsed);
tim.Interval = ;
tim.AutoReset = true;
}
7. 解决System不包含windows属性问题,引用程序集。
8.添加上面引用 的 tim_Elapsed 定时方法
private void tim_Elapsed(object sender, EventArgs e)
{
StartThread();
} /// <summary>
/// 开始任务
/// </summary>
private void StartThread()
{
MessageAdd(serviceName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
} /// <summary>
/// 日志记录
/// </summary>
/// <param name="serviceName">内容</param>
public void MessageAdd(string str)
{
try
{
fileclass.WriteLogFile(logPath, str);//写入记录日志
}
catch
{ }
}
9.此时生成解决方案是成功的
10.在OnStart等中写入自己的方法,这里用日志记录
protected override void OnStart(string[] args)
{
try
{
this.tim.Enabled = true;
this.tim.Start();
}
catch (Exception ex)
{
MessageAdd("OnStart错误:" + ex.Message);
}
MessageAdd(serviceName + "已成功启动!");
} protected override void OnStop()
{
try
{
this.tim.Stop();
}
catch (Exception ex)
{
MessageAdd("OnStop错误:" + ex.Message);
}
MessageAdd(serviceName + "已停止!");
} protected override void OnContinue()
{
this.tim.Start();
base.OnContinue();
} protected override void OnPause()
{
this.tim.Stop();
base.OnPause();
}
11.给服务添加安装程序。右键鼠标单击MainService.cs[设计]*选项卡选项“添加安装程序”。
12.可以看见项目中多了如下文件和组件,serviceProcessInstaller1、serviceInstaller1是自动生成的
13.设置组件serviceInstaller1的主要属性,StartType: AutoMatic自动启动;ServiceName: 服务系统标识,在cmd命令中执行sr start/stop/query等等命令时候使用,用来唯一标识一个Window服务
14.设置组件serviceProcessInstaller1的主要属性,Accout:账户类型,LocalSystem本地系统服务;
15.设置服务安装后“允许和桌面进行交互”,
需要在ProjectInstaller.cs中添加如下代码。
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq; namespace TerminalTrance
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
} protected override void OnAfterInstall(IDictionary savedState)
{ try
{ base.OnAfterInstall(savedState); // 允许服务桌面交互 System.Management.ManagementObject myService = new System.Management.ManagementObject(string.Format("Win32_Service.Name='{0}'", this.serviceInstaller1.ServiceName)); System.Management.ManagementBaseObject changeMethod = myService.GetMethodParameters("Change"); changeMethod["DesktopInteract"] = true; System.Management.ManagementBaseObject OutParam = myService.InvokeMethod("Change", changeMethod, null); } catch (Exception ex)
{ } }
}
}
16.Windows服务的安装和卸载
代码写完后,编译通过后,就可以安装、卸载、调试服务了。
在执行安装或卸载服务前,我有把服务需要的相关文件,复制到C:\Service\下面或其他路径。一旦安装完成后,此目录不能变更,否则不能卸载该服务和服务运行会报错。
安装、卸载很简单,只要在VS命令行导航到,服务程序的路径。然后运行以下命令就OK了。
打开如图:
安装服务:installutil C:\Service\TerminalTrance.exe
卸载服务:installutil /u C:\Service\TerminalTrance.exe
调试的话,只能先安装启动服务,然后将该服务附加到进程,就可以调试了。安装好服务后,就可以在win7服务管理里面,管理刚刚启动的服务了。
安装成功后可在服务中看到
在服务程序中可以看到添加的服务
可以看到程序的日志记录
另外一个方法是生成安装exe程序
1.解决方案右键=》新建项目=》选择安装程序
2.安装项目右键=》添加=》项目输出,选择主项目
3.安装项目右键=》视图=》自定义操作
4.自定义操作=》安装右键=》选择主输出
5.卸载右键=》选择主输出
6.若有文件需要添加到安装后的文件夹中=》点击应用程序文件夹=》添加=》文件,选择文件。安装后就会生成指定文件。
7.生成程序,完成,Setup文件夹中找到exe安装文件执行就 OK了。卸载也是执行此exe,按提示下一步就OK。
VS 2010一步步开发windows服务(windows service)的更多相关文章
- 用C#创建Windows服务(Windows Services)
用C#创建Windows服务(Windows Services) 学习: 第一步:创建服务框架 创建一个新的 Windows 服务项目,可以从Visual C# 工程中选取 Windows 服务(W ...
- C# windows服务:创建Windows服务(Windows Services)的一般步骤
C#创建Windows服务(Windows Services) Windows服务在Visual Studio 以前的版本中叫NT服务,在VS.net启用了新的名称.用Visual C# 创建Wind ...
- .net Windows服务程序和安装程序制作图解 及 VS 2010创建、安装、调试 windows服务(windows service)
.net Windows服务程序和安装程序制作 最近项目中用到window服务程序,以前没接触过,比较陌生,花了两天的时间学习了下,写了个简单的服务,但在制作安装程序的时候,参照网上很多资料,却都制作 ...
- C# VS 2010创建、安装、调试 windows服务(windows service)
在一个应用程序中创建多个 windows 服务的方法和 1083 的解决办法 错误解决方案 ------------------------------------------------------ ...
- VS创建、安装、调试 windows服务(windows service)
1.创建 windows服务 项目 文件 -> 新建项目 -> 已安装的模板 -> Visual C# -> windows ,在右侧窗口选择"windows 服 ...
- 创建Windows服务(Windows Services)N种方式总结
最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来.目前我知道的创建创建Windows服务有3种方式:a.利用.net框架类ServiceBaseb.利用组件Topshel ...
- (转)创建Windows服务(Windows Services)N种方式总结
转自:http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.html 最近由于工作需要,写了一些windows服务程序,有一些经验,我现在 ...
- 通过cmd 使用 InstallUtil.exe 命令 操作 windows服务 Windows Service
要安装windows service 首先要找到 InstallUtil.exe,InstallUtil.exe位置在 C:\Windows\Microsoft.NET\Framework\v4.0. ...
- C#开发Windows服务 附简单实例实现禁止QQ运行
本实例主要实现下面三个基本功能 1.C#开发windows服务 2.禁止QQ等程序运行 3.为windows服务创建自动安装程序 下面针对这三个基本功能进行实现 一.C#开发windows服务 Win ...
随机推荐
- PHP的输出缓冲区(转)
什么是缓冲区?简单而言,缓冲区的作用就是,把输入或者输出的内容先放进内存,而不显示或者读取.至于为什么要有缓冲区,这是一个很广泛的问题,如果有兴趣,可以在网山找下资料.其实缓冲区最本质的作用就是,协调 ...
- 输入框三种输入方式(selenium webdriver 干货)
在机票预定的页面,输入出发城市和到达城市输入框的时候, 发现直接使用sendkeys不好使, 大部分情况出现输入某城市后没有输入进去, 经过几天的研究,发现可以采取三种方式: 1. 先点击输入框,待弹 ...
- css确定元素水平居中和垂直居中
---恢复内容开始--- 首先,我们在了解如何通过css了解元素水平和垂直居中之前,先要了解下html都有哪些元素,这些元素与偶有哪些分类,因为不同类别的元素的水平垂直居中方法是完全不同的,究其根本当 ...
- for循环后面跟分号 - for (i = 0; i <= 3; i++);这不是错误语句
#include<iostream> int main() { using namespace std; ; ; i <= ; i++); t = t + i; cout <& ...
- ASP.NET Core中显示自定义错误页面-增强版
之前的博文 ASP.NET Core中显示自定义错误页面 中的方法是在项目中硬编码实现的,当有多个项目时,就会造成不同项目之间的重复代码,不可取. 在这篇博文中改用middleware实现,并且放在独 ...
- .Net组件程序设计之远程调用(二)
.Net组件程序设计之远程调用(二) 激活模式 引用封送对象激活类型两种, 一种是客户端激活类型,一种是服务器端激活. 客户端激活对象 客户端激活方式:当客户端创建一个远程对象时,客户端得到的是一个新 ...
- WCF服务创建与抛出强类型SOAP Fault
原创地址:http://www.cnblogs.com/jfzhu/p/4060666.html 转载请注明出处 前面的文章<WCF服务的异常消息>中介绍过,如果WCF Service发生 ...
- JS实战 · 实践积累点滴杂烩
onmouseover : 鼠标进入 onmouseout : 鼠标离开 onfocus:得到焦点 表单提交执行JS代码,有两种常用方式. 一:在局部(比如按钮定义处)用onclick=" ...
- JavaScript css-dom
HTML负责结构层,网页的结构层由HTML或者XHTML之类的标记语言负责构建 CSS负责表示层,描述页面内容应该如何呈现. JavaScript负责行为层,负责内容应该如何响应事件这一问题. 能利用 ...
- 【夔堂】:程序血泪史之——有一种垃圾语言叫做JavaScript
"Prototype"机制是个半成品OOP,有些文章说这玩意当初为了"简单(编写).容易(学习)"而发明的,但web前端技术发展到今天我们看到,JS显然是需要O ...