• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
浅时光
我喜欢,驾驭着代码在风驰电掣中创造完美!我喜欢,操纵着代码在随必所欲中体验生活!我喜欢,书写着代码在时代浪潮中完成经典!每一段新的代码在我手中诞生对我来说就象观看刹那花开的感动!
博客园    首页    新随笔    联系   管理    订阅  订阅

C#创建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 MyService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine("WindowsService: Service Started" + DateTime.Now.ToString() + "\n");

            sw.Flush();
            sw.Close();
            fs.Close();
        }

        //protected override void OnContinue()
        //{
        //    base.OnContinue();
        //}

        //protected override void OnPause()
        //{
        //    base.OnPause(); // father class method inherit
        //}

        //protected override void OnShutdown()
        //{
        //    base.OnShutdown();
        //}

        protected override void OnStop()
        {
            FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine("WindowsService: Service Stopped" + DateTime.Now.ToString() + "\n");
            sw.Flush();
            sw.Close();
            fs.Close();

        }
    }
}

在设计窗口添加安装程序,生成两个文件,修改其启动的服务名称、以及启动方式。

然后找到windows下.NET目录下InstallUtil.exe拖到服务目录下,执行InstallUtil 项目.exe添加服务。

注意:win7以上版本需要管理员权限。

posted @ 2016-09-30 10:28  浅时光  阅读(195)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3