您的位置:首页 > 编程语言 > C#

[转]C#创建服务及使用程序自动安装服务,.NET创建一个即是可执行程序又是Windows服务的exe

2015-05-08 21:21 1146 查看

写在前面

原文地址:C#创建服务及使用程序自动安装服务,.NET创建一个即是可执行程序又是Windows服务的exe

这篇文章躺在我的收藏夹中有很长一段时间了,今天闲着没事,就自己动手实践了一下。感觉作者还是蛮给力的。这里动手实践,把它变为自己的东西。多谢作者。

操作步骤

最近在弄的项目,一直在考虑是否弄windows服务来定时拉取数据。然后就按照这个思路,想了一下,发现跟之前看的一篇文章需求很是类似。就弄了个demo,把那种方式吸收下来。

首先,创建一个控制台应用程序。



然后,添加一个windows服务类。



项目



然后打开SericeHost.cs,右键查看代码



代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace Wolfy.SelfService
{
partial class ServiceHost : ServiceBase
{
public ServiceHost()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
System.IO.File.AppendAllText("D:\\log.txt", "Service Is Started……" + DateTime.Now.ToString());
}

protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
System.IO.File.AppendAllText("D:\\log.txt", "Service Is Stopped……" + DateTime.Now.ToString());
}
}
}


修改入口函数Main方法,根据agrs参数,来识别是安装服务,还是应用程序。如果是服务则执行安装服务的步骤,否则则运行程序。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace Wolfy.SelfService
{
class Program
{
static void Main(string[] args)
{
//如果传递了"s"参数就启动服务
if (args.Length > 0 && args[0] == "s")
{
//启动服务的代码,可以从其它地方拷贝
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ServiceHost(),
};
ServiceBase.Run(ServicesToRun);
}
else
{
Console.WriteLine("这是Windows应用程序");
Console.WriteLine("请选择,[1]安装服务 [2]卸载服务 [3]退出");
var rs = int.Parse(Console.ReadLine());
switch (rs)
{
case 1:
//取当前可执行文件路径,加上"s"参数,证明是从windows服务启动该程序
var path = Process.GetCurrentProcess().MainModule.FileName + " s";
Process.Start("sc", "create myserver binpath= \"" + path + "\" displayName= 我的服务 start= auto");
Console.WriteLine("安装成功");
Console.Read();
break;
case 2:
Process.Start("sc", "delete myserver");
Console.WriteLine("卸载成功");
Console.Read();
break;
case 3: break;
}
}

}
}
}


测试
以管理员身份运行Wolfy.SelfService.exe可执行程序。

这里需要注意,要以管理员身份运行,毕竟是安装windows服务,否则权限不够,造成安装失败。



输入1



然后win+R,输入services.msv





服务安装成功,下面我们启动服务。





查看下log.txt



说明服务安装成功,并启动成功。

停止服务,然后卸载服务。

Service Is Started……2015/5/8 21:14:11Service Is Stopped……2015/5/8 21:16:21


说明服务停止成功,然后进行卸载。



同样,卸载也要以管理员身份运行。

然后在服务管理中,发现“我的服务”已经卸载。

总结

这里按照作者的思路,进行了实践,这个思路确实不错,实践一下,也算吸收了。多谢。这篇文章也可以从我的收藏夹中移除了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐