
正文
webform调用windows服务
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
准备工作:
.电脑->管理->本地用户和组->组->Administrator双击->隶属->添加Network service->确定
.启动windows服务Windows Installer
.创建winform项目 WindowsFormsApplication1
.添加windows服务 service1
.添加代码
protected override void OnStart(string[] args)
{
if (args != null && args.Length > )
{
if (args[] == "")
{
string path = $@"d:\kxbbbb{DateTime.Now.ToLongDateString()}.txt";
File.Create($"{path}");
}
else if (args[] == "")
{
string path = $@"d:\kxqqq{DateTime.Now.ToLongDateString()}.txt";
File.Create($"{path}"); }
} // TODO: 在此处添加代码以启动服务。
}
.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);
}.service1.cs右键查看设计器,再右键添加安装程序,默认添加两个
serviceInstaller1和serviceProcessInstaller1
.serviceInstaller1右键属性修改Description 为这是一个测试服务
.serviceProcessInstaller1右键属性 Account修改为NetworkService
.管理员打开cmd
cd C:\Windows\Microsoft.NET\Framework(64)\v4.0.30319 把InstallUtil.exe复制到要发布的EXE的debug目录里面,命令切换等到该DEBUG目录
.安装服务
InstallUtil.exe WindowsFormsApplication1.exe
.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 = { "" };
service.Start(args);
service.WaitForStatus(ServiceControllerStatus.Running);
}






