
该服务以10S的间隔创建 d:/1.txt 文件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace WindowsServiceTest
{
publicpartialclassService1:ServiceBase
{
publicService1()
{
InitializeComponent();
}
protectedoverridevoidOnStart(string[] args)
{
//服务开启执行代码
StartDoSomething();
}
protectedoverridevoidOnStop()
{
//服务结束执行代码
}
protectedoverridevoidOnPause()
{
//服务暂停执行代码
base.OnPause();
}
protectedoverridevoidOnContinue()
{
//服务恢复执行代码
base.OnContinue();
}
protectedoverridevoidOnShutdown()
{
//系统即将关闭执行代码
base.OnShutdown();
}
privatevoidStartDoSomething()
{
System.Timers.Timer timer =newSystem.Timers.Timer(10000);//间隔10秒
timer.AutoReset=true;
timer.Enabled=false;//执行一次
timer.Elapsed+=newElapsedEventHandler(WriteSomething);
timer.Start();
}
privatevoidWriteSomething(object source,System.Timers.ElapsedEventArgs e)
{
FileStream fs =null;
try
{
fs =newFileStream("d:/1.txt",FileMode.OpenOrCreate);
string strText =@"以10秒的间隔重复创建该文件,若已有同名文件,则保持不变";
//获得字节数组
byte[] data =new UTF8Encoding().GetBytes(strText);
//开始写入
fs.Write(data,0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
fs.Dispose();
}
catch
{
}
finally
{
if(fs !=null)
{
fs.Close();
fs.Dispose();
}
}
}
}
}

2.将左上角第一个控件的Account属性设置为LocalService



1.生成解决方案(Ctrl+Shift+B),编译完成后会生成对应的xxx.exe

2.找到系统里面InstallUtil的安装目录 例如 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe 实在找不到就用Everything吧
3.Win+R CMD cd 跳转到InstallUtil的安装路径,运行如下命令 InstallUtil.exe+空格+4.1生成的exe的目录
cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
InstallUtil.exe E:\GitVSTest\WindowsServiceTest\WindowsServiceTest\bin\Debug\WindowsServiceTest.exe



原文:http://www.cnblogs.com/moonache/p/4644081.html