C#简单实现创建windows服务

本机环境:win10   64位   vs2017

1.新建WindowsService1

2.在设计页面单机右键->添加安装程序:

3.右键serviceProcessInstaller1,单击属性,将Account改为LocalSystem

同样右键serviceInstaller1,单击属性,将StartType改为Manual 

4.右键Service1.cs点击查看代码

扫描二维码关注公众号,回复: 4607528 查看本文章

5.这里我们实现开机自启一个socket服务端。修改代码如下 :

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.Threading.Tasks;
namespace WindowsService1
{

    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            //这是我要运行的控制台程序的路径,你用的时候换成你的就可以了
            string StartAppPath = @"C:\Users\biattt\Desktop\server\server\server\bin\Debug\server.exe";
        try
            {
                Process proc = new Process();
                proc.StartInfo.FileName = StartAppPath; //注意路径  
                proc.Start();
            }
            catch (System.Exception ex)
            {
                //错误处理 
                //这里可以打log
            }
            //这里可以打log
        }
        protected override void OnStop()
        {
            //这里可以打log
        }
    }
}

6.生成一下。关闭vs。

7.写bat脚本文件,用于安装和卸载服务。

安装脚本Install.bat:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe C:\Users\biattt\Desktop\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe
Net Start Service1
sc config Service1 start= auto
pause

其中第一行前半部分是你电脑安装服务的installutil.exe程序的地址,后半部分是你安装的服务的编译生成的exe文件地址。

卸载脚本:

net stop WindowsService1
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u C:\Users\biattt\Desktop\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe

 /u表示卸载。

8.以管理员身份运行Install.bat

9.这是打开任务管理器看看服务:

10.打开一个客户端,显示连接上了。说明服务真的布置上了!

11.在管理员身份运行Uninstall.bat。就看到这个服务没有了。

12.以上,就是 C#简单实现创建windows服务的过程。

猜你喜欢

转载自blog.csdn.net/maitianpt/article/details/82597917