一、创建Windows服务

使用VS创建一个新的windows服务应用程序

创建完成之后

二、相关配置

修改Service1名称为StartService(可以不改,自行选择

添加安装程序并修改配置

安装完成之后,源码中会出现一个ProjectInstaller程序集,双击进入页面修改相关属性

              

   

添加文件夹和实体类

LogHelper.cs

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace WindowsService.Common
{
public class LogHelper
{
/// <summary>
/// 获取程序异常信息
/// </summary>
/// <param name="methodBase"></param>
/// <param name="exception"></param>
/// <param name="message"></param>
/// <returns></returns>
public static string GetExceptionMessage(MethodBase methodBase, Exception exception, string message)
{
string fullName = methodBase.ReflectedType.FullName;
string name = methodBase.Name;
string str = $"\r\n异常综合信息(类:{fullName};函数名称:{name};):\r\n";
str += "-----------\r\n";
str += ".Net异常信息:\r\n";
if (exception == null)
{
str += " 无异常对象,也无堆栈信息(exception == null)\r\n";
}
else
{
str += $" {exception.Message}\r\n";
str += $".Net堆栈信息:\r\n{exception.StackTrace}\r\n";
}
str += "-----------\r\n";
if (message != null && message.Trim().Length > )
{
str += "===========\r\n";
str += $"自定义信息:\r\n {message}\r\n";
str += "===========\r\n";
}
return str;
} /// <summary>
/// 写出日志信息 目录地址:string logPath = AppDomain.CurrentDomain.BaseDirectory + "00_Log\\";
/// </summary>
/// <param name="folderName"></param>
/// <param name="message"></param>
public static void Write(string folderName, string message)
{
string text = AppDomain.CurrentDomain.BaseDirectory + "00_Log\\";
if (folderName != null && folderName.Trim().Length > )
{
text += folderName;
}
WritingLogs(text, message);
} /// <summary>
/// 写出异常日志(.txt)
/// </summary>
/// <param name="strPath"></param>
/// <param name="strContent"></param>
public static void WritingLogs(string strPath, string strContent)
{
FileStream fileStream = null;
StreamWriter streamWriter = null;
try
{
if (!Directory.Exists(strPath))
{
Directory.CreateDirectory(strPath);
}
strPath = string.Format("{0}\\{1}{2}", strPath, DateTime.Now.ToString("yyyy-MM-dd"), ".txt");
fileStream = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
streamWriter = new StreamWriter(fileStream);
streamWriter.BaseStream.Seek(0L, SeekOrigin.End);
streamWriter.WriteLine(strContent + "\r\n\r\n--------------------------------------------------------" + DateTime.Now.ToString() + "--------------------------------------------------------\r\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
finally
{
streamWriter.Close();
fileStream.Close();
}
} }
}

LogHelper

Utility.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace WindowsService.Common
{
public class Utility
{
/// <summary>
/// 是否到时间进行执行
/// </summary>
/// <param name="hour">当前时间(小时)</param>
/// <returns>true:时间已到;false:时间未到;</returns>
public static bool TimeOut(string hour)
{
string times = "14|20|01";
if (times == null || times.Trim().Length <= )
{
return false;
}
if (times.IndexOf('|') > )
{
foreach (string t in times.Split('|'))
{
if (t == hour)
{
return true;
}
}
}
else if (times == hour)
{
return true;
}
return false;
}
}
}

Utility

TaskStart.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WindowsService.Common; namespace WindowsService.BusinessServices
{
public class TaskStart
{ /// <summary>
/// 业务开始运行
/// </summary>
public void TaskProcessing()
{
LogHelper.Write("Start", ".....服务正式运行.....");
Thread.Sleep( * * ); //在20秒内进行附加进程
try
{
bool isRun = false; //默认不执行
while (true)
{
string hour = DateTime.Now.ToString("HH"); //获得当前的时间
isRun = Utility.TimeOut(hour) ? true : false;
if (isRun)//判断服务是否运行
{
#region 具体业务 LogHelper.Write("具体业务", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, Guid.NewGuid().ToString())); #endregion isRun = false; //已经操作一次
Thread.Sleep( * * ); //休眠 62 分钟 //必须要超过 一个 小时
}
else
{
//睡眠两分钟
Thread.Sleep( * * ); //停止设定时间,精确度比Sleep高
}
}
}
catch (Exception ce)
{
LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), ce, "\r\n\r\n.....服务异常.....\r\n\r\n")); ServiceController service = new ServiceController(new StartService().ServiceName);
service.Stop(); //停止服务
//service.Pause();//暂停服务
//service.Start();//开始服务
}
}
}
}

TaskStart(具体业务)

修改启动服务代码

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WindowsService.BusinessServices;
using WindowsService.Common; namespace WindowsService
{
public partial class StartService : ServiceBase
{
/// <summary>
/// 当前服务是否停止(默认时flase)
/// </summary>
private bool isStop = false; /// <summary>
/// 启动服务
/// </summary>
public StartService()
{
InitializeComponent(); this.CanPauseAndContinue = true;
this.CanStop = true;
isStop = false;
} ///<summary>
///暂停服务
///</summary>
protected override void OnPause()
{
LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....暂停服务.....\r\n\r\n"));
isStop = true; //服务暂停
} ///<summary>
///恢复服务
///</summary>
protected override void OnContinue()
{
LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....继续服务.....\r\n\r\n"));
isStop = false; //继续服务
} /// <summary>
/// 服务停止
/// </summary>
protected override void OnStop()
{
LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....停止服务.....\r\n\r\n"));
isStop = true; //服务停止
} /// <summary>
/// 服务开始运行
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
try
{
//当服务没有停止时,开始具体业务
if (isStop == false)
{
Thread thread = new Thread(new ThreadStart(new TaskStart().TaskProcessing));
thread.Start();
}
}
catch (Exception ce)
{
LogHelper.Write("Error", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), ce, "\r\n\r\n.....停止服务.....\r\n\r\n"));
}
}
}
}

StartService

、服务安装

新建一个txt文本,输入以下内容,这里的WindowsService.exe 是程序路径,前面的路径是固定的,后面可变。修改txt文件名称为bat批处理文件,新建文本文档.txt——install.bat 。 然后右击 以管理员身份运行   这个批处理文件。这样服务就安装成功了。最后别忘记手动启动下这个服务。

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  F:\DownLoad\WindowsService\WindowsService\WindowsService\bin\Debug\WindowsService.exe
pause

、服务卸载

和服务安装步骤一样,输入以下内容。然后 以管理员身份运行 即可。

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u F:\DownLoad\WindowsService\WindowsService\WindowsService\bin\Debug\WindowsService.exe
pause

四、调试

源码地址:https://github.com/RainFate/WindowsServiceDemo/tree/master/WindowsService

C# Windows服务创建安装卸载的更多相关文章

  1. Windows服务的安装卸载及错误查找

    @echo off echo 清理原有服务项. . . %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil /U D:\abc\te ...

  2. WCF 下的windows服务的安装卸载

    安装:启动vs2010(如果是win2008要以管理员来启动)命令:installutil demo.exe 卸载:先在服务里停止这个服务,然后启动vs2010(如果是win2008要以管理员来启动) ...

  3. 通过批处理进行Windows服务的安装/卸载&启动/停止

    安装服务 @echo off set checked=2 set PATHS=%~sdp0 echo 按任意键执行安装……? pause>nul if %checked% EQU 2 ( %PA ...

  4. .net windows 服务创建、安装、卸载和调试

    原文:http://blog.csdn.net/angle860123/article/details/17375895 windows服务应用程序是一种长期运行在操作系统后台的程序,它对于服务器环境 ...

  5. Windows服务一:新建Windows服务、安装、卸载服务

    Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面 ...

  6. Windows服务创建及安装

    Windows服务创建及安装http://www.cnblogs.com/tuyile006/archive/2006/11/27/573654.html

  7. C#操作windows服务,安装、卸载、停止、启动

    public class ServiceUtil { private string _ServiceName = string.Empty; private string _AppName = str ...

  8. 使用InstallUtil对Windows服务进行安装与卸载

    关于Visual Studio 2012中使用InstallUtil对Windows服务进行安装与卸载的文章,在MSDN中的http://msdn.microsoft.com/en-us/librar ...

  9. windows服务创建与管理

    安装windows 服务 C:\Users\chensimin>cd \ C:\>cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 C:\W ...

随机推荐

  1. Codeforces Round #597 (Div. 2) E. Hyakugoku and Ladders 概率dp

    E. Hyakugoku and Ladders Hyakugoku has just retired from being the resident deity of the South Black ...

  2. 趣谈Linux操作系统学习笔记:第二十五讲

    一.mmap原理 在虚拟内存空间那一节,我们知道,每一个进程都有一个列表vm_area_struct,指向虚拟地址空间的不同内存块,这个变量名字叫mmap struct mm_struct { str ...

  3. 不用输入ssh -i命令行即可携带pem文件快速登录的方法

    如果要登录的服务器只允许pem认证 每次输入ssh -i xxxx.pem 用户@ip 地址  就很烦 这里有个一劳永逸的方法: 进入到自己的用户目录,例如/home/me 把pem文件放在当前目录 ...

  4. 打造IP代理池,Python爬取Boss直聘,帮你获取全国各类职业薪酬榜

    爬虫面临的问题 不再是单纯的数据一把抓 多数的网站还是请求来了,一把将所有数据塞进去返回,但现在更多的网站使用数据的异步加载,爬虫不再像之前那么方便 很多人说js异步加载与数据解析,爬虫可以做到啊,恩 ...

  5. 1+x 证书 Web 前端开发中级理论考试(试卷 6 )

    1+x 证书 Web 前端开发中级理论考试(试卷 6 ) 官方QQ群 1+x 证书 web 前端开发初级对应课程分析 http://blog.zh66.club/index.php/archives/ ...

  6. JNDI和JDBC的区别-个人理解

    网上关于JNDI和JDBC的定义有很多,但是都很官方不容易理解,下面是我最近查阅资料得出的心得体会.希望对你在理解上有一点点的帮助,说的不对的请指正哦. JDBC: 看到最多的就是 Java Data ...

  7. Django JsonResponse 不自动设置 cookie 的解决方案

    [背景] 目前在做一个前后端分离的 web 项目,后端使用的是 django 框架,所有的 API 都只返回 json :就在这个过程中遇到了一个问题,那就是对于所有的 JsonResponse dj ...

  8. [转]scala和RDD中的占位符"_"

    1.通配符.类似Java中的*.如:import scala.math._ 2.作为一个整体.:_*,告诉编译器你希望将某个参数当作参数序列处理!例如val s = sum(1 to 5:_*)就是将 ...

  9. 关于WIN7下IE8IE7浏览器无法安装微信支付商户证书的解决方案

    关于WIN7下IE8IE7浏览器无法安装微信支付商户证书的解决方案 解决方案就是使用 chrome浏览器 默认的chorme浏览器  打开微信商户平台 会提示让安装控件  然后反复安装 其实要解决这个 ...

  10. 【IDEA】(1)---MAC下常用快捷键

    IDEA常用快捷键 IDEA是一个很好的开发工具,用好它能大大提高我们的开发效率,所以这里学习总结下有关IDEA实用的一些教程,比如常用快捷键,如何自定义代码模版,如何debug异常断点,或者说多线程 ...