准备工作:
0.电脑->管理->本地用户和组->组->Administrator双击->隶属->添加Network service->确定
1.启动windows服务Windows Installer
2.创建winform项目 WindowsFormsApplication1
3.添加windows服务 service1
4.添加代码
protected override void OnStart(string[] args)
{
if (args != null && args.Length > 0)
{
if (args[0] == "1")
{
string path = $@"d:kxbbbb{DateTime.Now.ToLongDateString()}.txt";
File.Create($"{path}");
}
else if (args[0] == "2")
{
string path = $@"d:kxqqq{DateTime.Now.ToLongDateString()}.txt";
File.Create($"{path}");
}
}
// TODO: 在此处添加代码以启动服务。
}
5.Main函数启动
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
ServiceBase[] serviceRun;
serviceRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(serviceRun);
}
6.service1.cs右键查看设计器,再右键添加安装程序,默认添加两个
serviceInstaller1和serviceProcessInstaller1
7.serviceInstaller1右键属性修改Description 为这是一个测试服务
8.serviceProcessInstaller1右键属性 Account修改为NetworkService
9.管理员打开cmd
cd C:WindowsMicrosoft.NETFramework(64)v4.0.30319 把InstallUtil.exe复制到要发布的EXE的debug目录里面,命令切换等到该DEBUG目录
10.安装服务
InstallUtil.exe WindowsFormsApplication1.exe
11.webform调用
protected void Page_Load(object sender, EventArgs e)
{
ServiceController service = new ServiceController("Service1");
//if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
//{
// service.Start();//打开服务
//}
//停止服务
service.Stop();//这行报错:无法打开计算机“.”上的 Service1 服务。
service.WaitForStatus(ServiceControllerStatus.Stopped);
//启动服务
string[] args = { "2" };
service.Start(args);
service.WaitForStatus(ServiceControllerStatus.Running);
}