C#写Windows 服务

it2022-05-30  80

C#写Windows 服务

一、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(或者根据需要设定其他项)

 

posted on 2010-08-20 15:27 彬子 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/wangzb/archive/2010/08/20/1804633.html

相关资源:C#实现Windows服务创建、安装

最新回复(0)