C# window service

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

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        private string fileName = @"C:/發佈/log.txt";
        private System.Timers.Timer _timer;

        public Service1()
        {
            MakeFile(fileName, "服務正在初始化");
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            MakeFile(fileName, "服務開始啓動");

            _timer = new System.Timers.Timer();
            _timer.Interval = 2000;
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
            _timer.Start();
        }

        void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            MakeFile(fileName, "現在時間是:" + DateTime.Now);
        }

        protected override void OnStop()
        {
            MakeFile(fileName, "服務已經結束");
        }


        public static void MakeFile(string FileName, string Content)
        {
            System.IO.StreamWriter sw = new System.IO.StreamWriter(FileName, true, System.Text.Encoding.GetEncoding("gb2312"));
            try
            {
                sw.WriteLine(Content);
                sw.Flush();
            }
            finally
            {
                if (sw != null) sw.Close();
            }
        }
    }
}

 

 

 部署:

 

 1.設計模式下右鍵-->添加安裝程序-->設置serviceProcessInstaller1的Account爲LocalSystem

 

2.設置serviceInstaller1的StartType爲Automatic

 

 3.編譯

 

4.在命令模式下執行:%systemroot%/microsoft.net/framework/v2.0.50727/installUtil.exe D:/項目目錄/bin/Debug/可執行文件名.exe

 

 

 

刪除服務: 

 

 使用SC命令

sc delete 服務名

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章