C# windows service 创建 、调试、部署

查看windows service

WIN+R  输入 services.msc 也可

右击我的电脑 》属性 》控制面板 》

找到管理工具 》双击 》

  

找到服务 ,事件查看器可以查看 service 运行 的事件 日志

 

方框对应下文中serviceIntaller.cs 中的

  Description(系统服务的描述) 

  DisplayName (系统服务中显示的名称)

创建

文件   》 新建项目 》选择windows 桌面  》Windows 服务 

输入项目名称 ,点击确定即可

双击H8900service.cs  》 

 

 

在空白处右击  选择添加安装程序 》

项目会自动生成安装文件 ProjectInstaller.cs ,接下来分别设置 serviceIntaller1 与 serviceProcessInstaller1 的属性 

.ProjectInstaller.cs设计页面中

    serviceInstaller1属性中设置:

    Description(系统服务的描述) 

    DisplayName (系统服务中显示的名称)

    ServiceName(系统事件查看器里的应用程序事件中来源名称)

    serviceProcessInstaller1属性设置:Account 下拉设置成 LocalSystem

 

projectIntaller.cs 代码:

设置服务启动方式为自动启动

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Threading.Tasks;

namespace H8900Service
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
            this.Committed += new InstallEventHandler(ProjectInstaller_Committed);
        }

        private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
        {
            //参数为服务的名字
            System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("H8900Service");
            controller.Start();
        }

        private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
        {

        }

        private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
        {

        }
    }
}

 

H8900service.cs 代码:

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

namespace H8900Service
{
    public partial class H8900service : ServiceBase
    {
        System.Timers.Timer timer1;  //计时器
        public H8900service()
        {
            InitializeComponent();
        }

            protected override void OnStart(string[] args)
            {
                EventLog.WriteEntry("H8900平台服务开始");         //在系统事件查看器里的应用程序事件里来源的描述
                writestr("服务启动");                                           //自定义文本日志
                timer1 = new System.Timers.Timer();               //计时器
                timer1.Interval = 1000;                                              //设置计时器事件间隔执行时间
                timer1.Elapsed += new ElapsedEventHandler(ChkService);       //到达时间执行的事件
                                                                             //  timer1.AutoReset = true;                                             //设置执行一次(false)还是一直执行(true)
                timer1.Enabled = true;                                               //是否执行Elasped 事件
            }

            private void TMStart1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                //执行SQL语句或其他操作
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\" + 1 + "log.txt", true))
                {
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
                }


            }


            /// <summary>
            /// 定时检查,并执行方法
            /// </summary>
            /// <param name="source"></param>
            /// <param name="e"></param>
            public void ChkService(object source, System.Timers.ElapsedEventArgs e)
            {
                int intHour = e.SignalTime.Hour;
                int intMinute = e.SignalTime.Minute;
                int intSecond = e.SignalTime.Second;

                if (intHour == 11 && intMinute == 30 && intSecond == 00) ///定时设置,判断分时秒
                {
                    try
                    {
                        System.Timers.Timer tt = (System.Timers.Timer)source;
                        tt.Enabled = false;
                        SetInnPoint();
                        tt.Enabled = true;
                    }
                    catch (Exception err)
                    {
                        writestr(err.Message);
                    }
                }
            }


            //我的方法
            public void SetInnPoint()
            {
                try
                {
                    writestr("服务运行");
                    //这里执行你的东西
                    EventLog.WriteEntry("下班啦");
                    Thread.Sleep(10000);
                }
                catch (Exception err)
                {
                    writestr(err.Message);
                }
            }

            ///在指定时间过后执行指定的表达式
            ///
            ///事件之间经过的时间(以毫秒为单位)
            ///要执行的表达式
            public static void SetTimeout(double interval, Action action)
            {
                System.Timers.Timer timer = new System.Timers.Timer(interval);
                timer.Elapsed += delegate (object sender, System.Timers.ElapsedEventArgs e)
                {
                    timer.Enabled = false;
                    action();
                };
                timer.Enabled = true;
            }


            public void writestr(string readme)
            {
                //debug==================================================
                //StreamWriter dout = new StreamWriter(@"c:\" + System.DateTime.Now.ToString("yyyMMddHHmmss") + ".txt");
                StreamWriter dout = new StreamWriter(@"c:\" + "WServ_InnPointLog.txt", true);
                dout.Write("\r\n事件:" + readme + "\r\n操作时间:" + System.DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
                //debug==================================================
                dout.Close();
            }

            protected override void OnPause()
            {
                //服务暂停执行代码
                base.OnPause();
            }
            protected override void OnContinue()
            {
                //服务恢复执行代码
                base.OnContinue();
            }
            protected override void OnShutdown()
            {
                //系统即将关闭执行代码
                base.OnShutdown();
            }


            protected override void OnStop()
            {
                writestr("服务停止");
                EventLog.WriteEntry("H8900平台服务停止");
                this.timer1.Enabled = false;
            }

        }
    }

安装、卸载window服务

方法1:

1、输入cmd(命令行),输入cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319,2.0为cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
2、安装服务(项目生成的exe文件路径)
  InstallUtil "E:\WindowsService1\bin\Debug\WindowsService1.exe"
3、卸载服务
  InstallUtil  /u "E:\WindowsService1\bin\Debug\WindowsService1.exe"

方法2:bat:

(安装)Install.bat

%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\installutil.exe WindowsService1.exe
 Net Start Service1
 sc config Service1 start= auto
 pause

卸载

%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /u WindowsService1.exe

我用的window10+ vs2015 

这里出了好多错

Microsoft(R) .NET Framework 安装实用工具版本 4.0.30319.1
Copyright (c) Microsoft Corporation.  All rights reserved.
在初始化安装时发生异常:
System.IO.FileNotFoundException: 未能加载文件或程序集“file:///C:\Users\Administrator\Documents\Visual”或它的某一个依赖项。系统找不到指定的文件。。

这个错误乍一看也是完全没有头绪,思考了很久,还是从报错信息入手,发现报错信息里提示的目录不完整,到"\Visual"就停止了,而实际的目录是\Visual Studio

使用.bat 来启动的话 注意service.exe 要使用绝对路径

把exe文件拿出来放置一个文件夹  成功解决


调试window服务
1、通过【事件查看器】查看
2、直接在程序中调试(菜单-->调试-->附加进程-->服务名(这里的服务名是项目名称,不是ServiceName属性自定义的名称,所以建议自定义名称和项目名称保持一致,另外需勾选【显示所有用户的进程】才能看到服务名)-->附加
3. 在程序中打断点调试即可,另外调试服务时服务必须已启动(管理工具-->服务)

 

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值