C# 创建Windows服务demo

一、准备工作

1.操作系统:Windows 10 X64

2.开发环境:VS2017

3.编程语言:C#

4. .NET版本:.NET Framework 4.5

二、创建Windows Service

1.新建一个Windows Service,并将项目名称改为“MyWinsService”,程序保存路径自己选一个,如下图所示:

2、在解决方案资源管理器内将Service1.cs改为MyService1.cs后,右键“查看代码”图标按钮进入代码编辑器界面,下面直接贴代码:

     string filePath = $"{Application.StartupPath}\\MyserviceLog.txt"; 
        protected override void OnStart(string[] args)
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Append))
            using (StreamWriter writer=new StreamWriter(stream))
            {
                writer.WriteLine(DateTime.Now +" "+"启动服务!");
            }
        }
        protected override void OnStop()
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine(DateTime.Now + " " + "停止服务!");
            }
        }

3.双击项目“MyWindowsService”进入“MyService”设计界面,在空白位置右击鼠标弹出上下文菜单,选中“添加安装程序”,如下图所示:

 4、进入页面之后就会看到serviceProcessInstaller1和serviceInstaller1;

点击“serviceProcessInstaller1”,在“属性”窗体将Account改为LocalSystem(服务属性系统级别),如下图所示:

5.点击“serviceInstaller1”,在“属性”窗体将ServiceName改为MyService,Description改为我的服务,StartType保持为Manual,如下图所示:

 

6.鼠标右键点击项目“MyWinsService”,在弹出的上下文菜单中选择“生成”按钮,生成我们自己的windows服务了。

三、创建安装、启动、停止、卸载服务的Windows窗体

1.我们以winform为例子吧,建一个简单的界面,这里命名为ServiveMan,修改属性text为windows服务管理,拖入四个Button,分别命名为安装、启动、停止、卸载

2.整理了一个Windows服务管理的类,这里我采用的是单例模式,如果有不理解的,我下一篇文章就分享一下单例模式。

    /// <summary>
    /// Windows服务管理
    /// </summary>
    public class serviceManager
    {
        private static serviceManager mSingle = null;
     //
public static serviceManager GetInstance() { if (mSingle == null) mSingle = new serviceManager(); return mSingle; }     //判断服务是否存在 private bool IsServiceExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController sc in services) { if (sc.ServiceName.ToLower() == serviceName.ToLower()) { return true; } } return false; } //安装服务 private void InstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; IDictionary savedState = new Hashtable(); installer.Install(savedState); installer.Commit(savedState); } } //卸载服务 private void UninstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; installer.Uninstall(null); } } //启动服务 private void ServiceStart(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Stopped) { control.Start(); } } } //停止服务 private void ServiceStop(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Running) { control.Stop(); } } }   }

3.接下来贴,windows服务管理类的使用方法,直接看代码,代码上都有注释

  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";
        string serviceName = "MyService";
        
        /// <summary>
        /// 事件:安装服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //判断是否存在服务 - 存在则开启服务
            if (serviceManager.GetInstance().IsServiceExisted(serviceName))
            {
                try
                {
                    serviceManager.GetInstance().ServiceStart(serviceName); //启动服务              
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            serviceManager.GetInstance().InstallService(serviceFilePath);//否则安装服务
        }

        /// <summary>
        /// 事件:启动Windows服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //启动Windows服务前判断是否存在Windows服务
            if (serviceManager.GetInstance().IsServiceExisted(serviceName))
            {
                try
                {
                    serviceManager.GetInstance().ServiceStart(serviceName);//开启Windows服务                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            else
            {
                //服务未安装
                DialogResult dr = MessageBox.Show("该服务尚未安装,是否安装服务?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.OK)
                {
                    serviceManager.GetInstance().InstallService(serviceFilePath);//安装服务
                }
                else
                {
                    return;
                }
            }
        }

        /// <summary>
        /// 事件:停止Windows服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (serviceManager.GetInstance().IsServiceExisted(serviceName))
            {
                try
                {                
                    serviceManager.GetInstance().ServiceStop(serviceName);//停止Windows服务
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        /// <summary>
        /// 事件:卸载Windows服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (serviceManager.GetInstance().IsServiceExisted(serviceName))
            {
                serviceManager.GetInstance().ServiceStop(serviceName);//停止Windows服务
                serviceManager.GetInstance().UninstallService(serviceFilePath);//卸载Windows服务
            }
        }       
  }

4、为了后续调试服务及安装卸载服务的需要,将已生成的MyWinsService.exe引用到本Windows窗体,右键添加引用,选择项目添加就可以了。这里就不上图了。

5.   安装服务,需要使用UAC中Administrator的权限,鼠标右击项目,在弹出的上下文菜单中选择“添加”->“新建项”,在弹出的选择窗体中选择“应用程序清单文件”并单击确定,如下图所示:

 

 5.打开该文件,并将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />,如下图所示:

 

6.整个过程完成了,现在我们可以启动项目了,启动后可能会弹出如下所示的窗体(有的系统因UAC配置有可能不显示),需要用管理员权限打开:

7.重启项目之后就可以了。

8、使用WIN+R的方式打开运行窗体,并在窗体内输入services.msc后打开服务,就可以看到下图:

9.我们可以通过刚刚写的开启服务来打开服务,如果服务不用了可以通过按钮直接停止或者卸载。

ok,今天关于windows服务的demo就分享到这了,如果有疑问的可以留言,讲的不对的欢迎指出!!!

posted @ 2019-06-28 10:01  Tulip123  阅读(673)  评论(0编辑  收藏  举报