标签:
该服务以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
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//服务开启执行代码
StartDoSomething();
}
protected override void OnStop()
{
//服务结束执行代码
}
protected override void OnPause()
{
//服务暂停执行代码
base.OnPause();
}
protected override void OnContinue()
{
//服务恢复执行代码
base.OnContinue();
}
protected override void OnShutdown()
{
//系统即将关闭执行代码
base.OnShutdown();
}
private void StartDoSomething()
{
System.Timers.Timer timer = new System.Timers.Timer(10000); //间隔10秒
timer.AutoReset = true;
timer.Enabled = false; //执行一次
timer.Elapsed += new ElapsedEventHandler(WriteSomething);
timer.Start();
}
private void WriteSomething(object source, System.Timers.ElapsedEventArgs e)
{
FileStream fs = null;
try
{
fs = new FileStream("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/4644091.html