一、Service的代码:
再添加完这些代码之后一定要记得“添加安装程序”
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 10000;
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
StreamWriter sw = null;
try
{
string filepath = AppDomain.CurrentDomain.BaseDirectory + @"\test.txt";
if (!File.Exists(filepath))
{
FileStream fs = File.Create(filepath);
fs.Close();
}
sw = File.AppendText(filepath);
sw.WriteLine("Timer ::-->" + DateTime.Now.ToString());
}
catch
{ }
finally
{
if (sw != null)
sw.Close();
}
}
protected override void OnStop()
{
}
}
二、安装Windows服务:
安装
installutil FileMonitorService.exe
卸载
installutil /u FileMonitorService.exe
参考:http://www.vchome.net/dotnet/dotnetdocs/dotnet38.htm
总结C#创建Windows的步骤:
1、创建项目,添加、关联执行代码。
2、创建Service的安装程序。
3、设定serviceProcessInstaller1的Account属性为LocalService(或者根据需要设定其他项)。
4、设定serviceInstaller1相对重要的几个属性:
Description:指示服务的说明。
ServiceName:指示系统用于标识此服务的名称。
StartType:指示启动此服务的方式和时间,一般设置成Automatic(或者根据需要设定其他项)
浙公网安备 33010602011771号