Window服务程序

ME的第一Window服务程序,记一笔。
使用vs.net 2005添加项目,选择window服务程序,添加System.Timers.Timer定时器;代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;

namespace WindowsService1
{
    
public partial class Service1 : ServiceBase
    {
        
private System.Timers.Timer timer1;
        
public Service1()
        {
            InitializeComponent();
            this.timer1 = new System.Timers.Timer();
            this.timer1.Interval = 30000;
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
        }
        
protected override void OnStart(string[] args)
        {
            
// TODO: 在此处添加代码以启动服务。
            this.timer1.Enabled = true;
            
this.LogMessage("服务启动");
        }

        
protected override void OnStop()
        {
            
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。

            
this.timer1.Enabled = false;
            
this.LogMessage("服务停止");
        }
        
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            
this.LogMessage("服务开始运行");
        }

        
public void LogMessage(string cueString)
        {
            
string filename = "test.log";
            
//定义文件信息对象
            FileInfo info = new FileInfo(filename);
            
if (!info.Exists)
            {
                info.Create();
            }
            
//创建只写文件流
            using (FileStream fs = info.OpenWrite())
            {

                
///根据上面创建的文件流创建写数据流
                StreamWriter w = new StreamWriter(fs);

                
///设置写数据流的起始位置为文件流的末尾
                w.BaseStream.Seek(0, SeekOrigin.End);

                w.Write(
"\n"+cueString);

                
///写入当前系统时间并换行
                w.Write("{0} {1} \r\n", DateTime.Now.ToLongTimeString(),
                    DateTime.Now.ToLongDateString());

                
///写入日志内容并换行
                w.Write("\n");

                
///写入------------------------------------“并换行
                w.Write("------------------------------------\n");

                
///清空缓冲区内容,并把缓冲区内容写入基础流
                w.Flush();

                
///关闭写数据流
                w.Close();
            }
        }
    }
}


C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727使用InstallUtil.exe安装服务,具体如下:
开始-》运行cmd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>installutil E:\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe 安装,下载只需-u
原文地址:https://www.cnblogs.com/jinweida/p/1258998.html