我的第一个Windows服务

代码:

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.Tasks; 

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        //定时器  
        System.Timers.Timer t = null;  

        public Service1()
        {
            InitializeComponent();
            //启用暂停恢复  
            base.CanPauseAndContinue = true;

            //每5秒执行一次  
            t = new System.Timers.Timer(5000);
            //设置是执行一次(false)还是一直执行(true);  
            t.AutoReset = true;
            //是否执行System.Timers.Timer.Elapsed事件;  
            t.Enabled = true;
            //到达时间的时候执行事件(theout方法);  
            t.Elapsed += new System.Timers.ElapsedEventHandler(theout);  
        }

        protected override void OnStart(string[] args)
        {
            string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "启动";
            WriteLog(state);  
        }

        protected override void OnStop()
        {
            string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "停止";
            WriteLog(state);  
        }
        //恢复服务执行  
        protected override void OnContinue()
        {
            string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "继续";
            WriteLog(state);
            t.Start();
        }

        //暂停服务执行  
        protected override void OnPause()
        {
            string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "暂停";
            WriteLog(state);

            t.Stop();
        }


        public void WriteLog(string str)
        {
            using (StreamWriter sw = File.AppendText(@"d:\service.txt"))
            {
                sw.WriteLine(str);
                sw.Flush();
            }
        }

        public void theout(object source, System.Timers.ElapsedEventArgs e)
        {

            WriteLog("theout:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
        }  
    }
}

 

打开ProjectInstaller,修改serviceInstaller1组件属性

Description= 我的服务备注                       服务备注说明

DisplayName=我的服务                            服务友好名字 

ServiceName=MyService                         安装服务器名字

StartType=Automatic                                服务类型

Manual      服务安装后,必须手动启动。

Automatic    每次计算机重新启动时,服务都会自动启动。

Disabled     服务无法启动。

并设计serviceProcessInstaller1的属性Account=LocalSystem

如果将Account设置成User,安装时就会:

 

安装windows服务要有installutil.exe,这个在安装vs的时候已经有了

看看自己windows服务的系统版本和net版本找到installutil.exe,

我的是在:C:\Windows\Microsoft.NET\Framework\v4.0.30319

并把它复制到新建服务的bin/debug里面,就是跟windows服务的exe在一个文件夹里,这样后面安装比较好

安装

dos到windows服务所在文件夹

installutil.exe WindowsService1.exe

安装好了以后可以在服务里面查看

卸载

installutil.exe -u WindowsService.exe

 点击服务启动

报错

 这个只要把服务权限选项卡设置everyone就可以了

查看输出文件

第三个启动是重新启动,服务先停后启

 

自己手动编写代码安装,卸载windows服务

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public string serviceName = "Service1";
        private void button1_Click(object sender, EventArgs e)
        {
            string[] args = { "WindowsService1.exe" };//要安装的服务文件(就是用 InstallUtil.exe 工具安装时的参数)  
            ServiceController svcCtrl = new ServiceController(serviceName);
            if (!ServiceIsExisted(serviceName))
            {
                try
                {
                    System.Configuration.Install.ManagedInstallerClass.InstallHelper(args);
                    MessageBox.Show("服务安装成功!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
            else
            {
                MessageBox.Show("该服务已经存在,不用重复安装。");
            }  
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (ServiceIsExisted(serviceName))
                {
                    //UnInstall Service  
                    System.Configuration.Install.AssemblyInstaller myAssemblyInstaller = new System.Configuration.Install.AssemblyInstaller();
                    myAssemblyInstaller.UseNewContext = true;
                    myAssemblyInstaller.Path = "WindowsService1.exe";
                    myAssemblyInstaller.Uninstall(null);
                    myAssemblyInstaller.Dispose();
                    MessageBox.Show("卸载服务成功!");
                }
                else
                {
                    MessageBox.Show("服务不存在!");
                }

            }
            catch (Exception)
            {
                MessageBox.Show("卸载服务失败!");
            }  
        }

        /// <summary>  
        /// 检查指定的服务是否存在  
        /// </summary>  
        /// <param name="serviceName">要查找的服务名字</param>  
        /// <returns></returns>  
        private bool ServiceIsExisted(string svcName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == svcName)
                {
                    return true;
                }
            }
            return false;
        } 
    }
}

要把生成的exe跟要安装的windows服务exe放在一起,这样可以不用instuallutil.exe就可以安装,卸载了

在卸载是可能会出现服务没有被卸载,状态变成禁用的情况,这种请把服务管理窗口关掉就可以了

源码

=======================================

使用Windows批处理文件,例如添加一个Rongzi.RZR.ProcessExcelServie服务

install.bat:

sc create "Rongzi.RZR.ProcessExcelServie" binpath= "%~dp0Rongzi.RZR.ProcessExcel.Sub.exe"
sc description Rongzi.RZR.ProcessExcelServie "东方融资网融资人粒子导入数据服务"
sc failure "Rongzi.RZR.ProcessExcelServie" reset= 3600 actions= restart/500/restart/5000/restart/30000
sc start "Rongzi.RZR.ProcessExcelServie"

uninstall.bat:

sc stop "Rongzi.RZR.ProcessExcelServie"
sc delete "Rongzi.RZR.ProcessExcelServie"

 

http://blog.csdn.net/angle860123/article/details/17375895

https://www.cnblogs.com/pingming/p/5108947.html

posted @ 2015-05-17 19:11  hongdada  阅读(468)  评论(0编辑  收藏  举报