VS2013创建Windows服务与调试服务的图文方法

这篇文章主要介绍了VS2013创建Windows服务与调试服务的图文方法,需要的朋友可以参考下

1、创建Windows服务

 

说明:

a)Description 服务描述,直接显示到Windows服务列表中的描述;

b)DisplayName 服务显示名称,直接显示到Windows服务列表中的名称;

c)ServiceName 服务进程名称,安装与卸载服务时的唯一标识。

单击“serviceProcessInstaller1”,在其属性窗口中设置Account帐号方式,建议为LocalService(当然也可以Account属性改为 LocalSystem,这样,不论是以哪个用户登录的系统,服务总会启动)。

编写安装和卸载脚本,并将放在bin/debug或bin/Release文件夹下。

安装脚本

 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe %~dp0exe程序的名称.exe Net Start 服务名称 sc config 服务名称 start= auto pause

这里注意,在exe程序的名称前面有 %~dp0 这是代表当前位置

服务名称 对应 上面我们创建服务时ServerName的名称

卸载脚本

 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u %~dp0exe程序的名称.exe pause

同时还要注意一下,本人用的.NET4.0的版本,所以\Microsoft.NET\Framework\v4.0.30319\installutil.exe 这一段要根据你机器安装.NET的版本来定。

其实脚本主要是通过installutil.exe 来进行安装和卸载服务的,同时此处涉及的批处理命令不多。

2、调试windows服务

在项目中不用启动windows服务项目,而是直接附加进程来进行调试。

 

在可用进程中,查找到你刚才通过脚本安装的服务就可以了。

再发一个写入服务代码的Demo

 public partial class MMSServer : ServiceBase { private Timer time = new Timer(); public MMSServer() { InitializeComponent(); } protected override void OnStart(string[] args) { #if DEBUG if (!Debugger.IsAttached) Debugger.Launch(); Debugger.Break(); #endif WriteLog("服务启动,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n"); time.Elapsed += new ElapsedEventHandler(MethodEvent); time.Interval = 3 * 1000; time.Start(); } protected override void OnPause() { #if DEBUG if (!Debugger.IsAttached) Debugger.Launch(); Debugger.Break(); #endif WriteLog("服务暂停,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n"); base.OnPause(); } protected override void OnContinue() { #if DEBUG if (!Debugger.IsAttached) Debugger.Launch(); Debugger.Break(); #endif WriteLog("服务恢复,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n"); base.OnContinue(); } protected override void OnShutdown() { WriteLog("计算机关闭,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n"); base.OnShutdown(); } private void MethodEvent(object source, System.Timers.ElapsedEventArgs e) { time.Enabled = false; string result = string.Empty; try { //......... result = "执行成功,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n"; } catch (Exception ex) { result = "执行失败,原因:" + ex.Message + "\r\n"; } finally { WriteLog(result); time.Enabled = true; } } protected override void OnStop() { #if DEBUG if (!Debugger.IsAttached) Debugger.Launch(); Debugger.Break(); #endif WriteLog("服务停止,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n"); } ///  /// 日志记录 ///  ///  private void WriteLog(string logInfo) { try { string logDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\Logs"; if (!Directory.Exists(logDirectory)) { Directory.CreateDirectory(logDirectory); } string filePath = logDirectory + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; File.AppendAllText(filePath, logInfo); } catch { } } }

以上就是关于VS2013创建Windows服务与调试服务的全部内容了,希望大家以后多多支持html中文网

以上就是VS2013创建Windows服务与调试服务的图文方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程