EasyService4Net - 在 100 秒或更短时间内创建一个 Windows 服务
如何轻松创建可以作为控制台程序或 Windows 服务运行的程序,并在不使用 installutil 的情况下安装它
引言
如果你曾经想创建一个新的 Windows 服务,并且希望它也能作为控制台程序运行,你就会知道这可能会非常令人烦恼,并且需要花费大量时间。
在本技巧中,我将解释如何非常轻松地做到这一点。
Using the Code
打开一个新的 Visual Studio 控制台应用程序,并将 EasyService4Net
nuget 包添加到它
在 Program.cs 文件中,添加 usings
using System.IO;
using EasyService4Net;
在 Main
函数中编写以下代码
static void Main(string[] args)
{
var easyService = new EasyService();
easyService.OnServiceStarted +=
() => File.WriteAllText("C:\\exampleFile.txt", "Hello World!");
easyService.Run(args);
}
在这里,你可以编写服务启动时想要运行的代码。在这个例子中,它将在文件中写入 "Hello World
"。
现在你需要向项目中添加两个空类(如果没有,Windows 服务将无法工作!)
using EasyService4Net.ServiceInternals;
public class EasyServiceInstaller : ProjectInstaller { }
public class EasyServiceService : InternalService { }
并向项目添加两个引用
System.Configuration.Install
System.ServiceProcess
完成了,现在你可以将服务安装为 Windows 服务
以管理员身份运行 cmd(为了安装 Windows 服务,你必须是管理员),进入编译后的代码所在的文件夹,并输入(如果你的 EXE 文件名为 MyEasyService
)
MyEasyService.exe -install
你的 Windows 服务正在运行
你可以输入 services.msc 查看它
如果你打开文件 "C:\\example.txt",你将看到其中写入了 "Hello World
"。
如果你想卸载服务,你只需要执行以下操作
MyEasyService.exe -uninstall
请注意,你也可以将此程序作为控制台程序运行(以管理员身份)。
注释
- EasyService4Net 的 GitHub - https://github.com/TheCodeCleaner/EasyService4Net
- 如果你不想依赖 EasyService4Net nuget,你可以简单地将其代码添加到你的项目中,并自行管理它。
- StackOverflow 上的答案,关于如何默认以管理员身份运行应用程序(非常有用)- http://stackoverflow.com/questions/2818179/how-to-force-my-net-app-to-run-as-administrator-on-windows-7
- 我希望你喜欢这个技巧,并从现在开始将其用于你的 Windows 服务。
- 欢迎提出任何建议或你发现的问题。