C# 编写Windows Service(windows服务程序)

  • 用C#创建Windows服务的步骤: 

创建Windows Service项目

从Visual C# 工程中选取 Windows 服务(Windows Service)选项,给工程一个新文件名,然后点击 确定。

起名规则一般是WindowsService+项目名

 

设计界面,右键-》添加安装程序

出现下图

右键属性,设置服务名(这个服务名是安装后在服务里查看到的名称)

 设置Account-----》LocalSystem

 

在设计界面右键查看代码:

添加定时执行代码

protected override void OnStart(string[] args)
        {
            //Debugger.Launch();
            System.Timers.Timer t = new System.Timers.Timer();
            var times = Double.Parse(System.Configuration.ConfigurationManager.AppSettings["timers"]) * 60 * 1000;
            t.Interval = times;
            t.Elapsed += new System.Timers.ElapsedEventHandler(TMStart1_Elapsed);//到达时间的时候执行事件; 
            t.Start();
            //TMStart1_Elapsed();  //方便在VS中调试用
        }

 

static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {

            Service1 service = new Service1();
            service.Test(null);  //便于Vs调试

            while (true)
            {
                System.Threading.Thread.Sleep(1000);
            }
            return;

            //ServiceBase[] ServicesToRun;
            //ServicesToRun = new ServiceBase[] 
            //{ 
            //    new Service1() 
            //};
            //ServiceBase.Run(ServicesToRun);
        }
    }
View Code
//调试入口
public void Test(string[] args)
        {
            OnStart(args);   
        }

 

 

服务停止时执行的方法:

 protected override void OnStop()
        {
            //using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))
            //{
            //    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "服务Stop.");
            //}
        }

 

 

定时方法:

 public void TMStart1_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
 //这里处理你需要定时执行的任务
}

上面方法在VS中调试时可以改为//public void TMStart1_Elapsed(){}

 

日志记录:

 /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="logInfo"></param>
        private void WriteLog(string logInfo)
        {
            try
            {
                string logDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
                if (!Directory.Exists(logDirectory))
                {
                    Directory.CreateDirectory(logDirectory);
                }
                string filePath = logDirectory + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                File.AppendAllText(filePath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + logInfo + "\r\n");
            }
            catch
            {

            }
        }

 

服务安装脚本,生成bat文件,格式为ANSI

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe D:\WinService\Release\WindowsServiceOutOfStorage.exe
Net Start ServiceOutOfStorage
sc config ServiceOutOfStorage start= auto
pause

 

卸载脚本

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u D:\WinService\Release\WindowsServiceOutOfStorage.exe
pause

 

posted @ 2017-07-06 19:44  SmilePastaLi  阅读(207)  评论(0编辑  收藏  举报