第一步、新建windows服务(版本是Microsoft Visual Studio 2010),如下图所示:
第二部、双击Service1.cs文件
第三部、鼠标移到下图所示位置,右键选择“添加安装程序”,然后会自动新建“ProjectInstaller.cs类文件”包含两个类“serviceProcessInstaller1”和“serviceInstaller1” 。
点击serviceProcessInstaller1右键属性将“Account”改为LocalService,点击serviceInstaller1将属性“StartType”改为Automatic 。
第四步、双击Service1.cs ,右键查看源码如下图:
源码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
}
在OnStart(string[] args){} 函数中写入需要的服务功能,(如下是我自己的服务需要处理的事情)
protected override void OnStart(string[] args)
{
//服务开启执行代码
StartDoSomething();
}
protected override void OnStop()
{
}
private void StartDoSomething()
{
System.Timers.Timer timer = new System.Timers.Timer(82800000); //间隔10秒
timer.AutoReset = true;
timer.Enabled = false; //执行一次
timer.Elapsed += new ElapsedEventHandler(WriteSomething);
timer.Start();
}
private void WriteSomething(object source, System.Timers.ElapsedEventArgs e)
{
string filePath = @"D:\WEB\Manage\DownLoad";
DeleteDir(filePath);
}
public static bool DeleteDir(string strPath)
{
try
{ // 清除空格
strPath = @strPath.Trim().ToString(); // 判断文件夹是否存在
if (System.IO.Directory.Exists(strPath))
{ // 获得文件夹数组
string[] strDirs = System.IO.Directory.GetDirectories(strPath); // 获得文件数组
string[] strFiles = System.IO.Directory.GetFiles(strPath); // 遍历所有子文件夹
foreach (string strFile in strFiles)
{ // 删除文件夹
System.IO.File.Delete(strFile);
} // 遍历所有文件
foreach (string strdir in strDirs)
{ // 删除文件
System.IO.Directory.Delete(strdir, true);
}
} // 成功
return true;
}
catch (Exception Exp) // 异常处理
{ // 异常信息
System.Diagnostics.Debug.Write(Exp.Message.ToString()); // 失败
return false;
}
}
第四步、确认功能无误,然后生成项目。
第五步、安装服务
1、下载InstallUtil.exe (需要借助InstallUtil.exe安装)或者引用.net中的InstallUtil.exe默认路径为(“C:\Windows\Microsoft.NET\Framework\v4.0.30319”)安装过程如果出现安装失败有可能是InstallUtil.exe的版本太低,所以引用的时候尽可能用搞版本的InstallUtil.exe。
2、安装方法:运行 cmd 找到InstallUtil.exe文件位置和服务的生成文件,我的实例如下
然后回车
进入任务管理器,找到新建的服务,启动即可
注释:删除服务cmd -> sc delete 服务名
注:如果安装失败,且失败原因提示:Windows服务安装异常:System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件日志。不可 访问的日志: Security
解决方法:cmd.exe 右键以管理员身份运行再重复以上的安装步骤