安装后自动启动服务
Starting service automatically after installation
这是一个使用 VS2015 和 .NET Framework 4.5 的 Windows 服务项目。
我正在尝试通过 post-build 操作安装我的服务,然后使用 ServiceController.Start()
自动启动它。这是我尝试启动服务的代码:
private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
{
using (var sw = new System.IO.StreamWriter(Console.OpenStandardOutput()))
{
using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName))
{
try
{
sw.Write("Starting service...");
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
sw.Write("Service status is now set to {0}.", sc.Status.ToString());
}
catch (InvalidOperationException)
{
sw.Write("Could not start the service.");
}
}
}
}
服务安装得很好,但我的 ServiceController.WaitForStatus()
电话似乎一直在等待。我试过从 Committed
和 AfterInstall
事件调用它。
终于想通了。我的 Start()
调用实际上失败了,直到我转到事件查看器时我才注意到。错误消息类似于:
Your process does not have access rights to this namespace
谷歌搜索错误消息 another SO post 接受的答案对我有用。希望这对以后的人有所帮助。
这是一个使用 VS2015 和 .NET Framework 4.5 的 Windows 服务项目。
我正在尝试通过 post-build 操作安装我的服务,然后使用 ServiceController.Start()
自动启动它。这是我尝试启动服务的代码:
private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
{
using (var sw = new System.IO.StreamWriter(Console.OpenStandardOutput()))
{
using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName))
{
try
{
sw.Write("Starting service...");
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
sw.Write("Service status is now set to {0}.", sc.Status.ToString());
}
catch (InvalidOperationException)
{
sw.Write("Could not start the service.");
}
}
}
}
服务安装得很好,但我的 ServiceController.WaitForStatus()
电话似乎一直在等待。我试过从 Committed
和 AfterInstall
事件调用它。
终于想通了。我的 Start()
调用实际上失败了,直到我转到事件查看器时我才注意到。错误消息类似于:
Your process does not have access rights to this namespace
谷歌搜索错误消息 another SO post 接受的答案对我有用。希望这对以后的人有所帮助。