作为Windows服务安装问题的控制台应用程序
问题描述:
我将控制台应用程序更改为使用ServiceBase作为Windows服务。我使用以下命令安装它。但我没有找到服务的服务。我查了日志,它说作为Windows服务安装问题的控制台应用程序
“与RunInstallerAttribute.Yes没有公开的安装属性可以在C中找到:\测试\ MyService.exe集结号”
如何创建控制台应用程序的安装程序?请告诉我。
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" "c:\MyService.exe"
using System.ServiceProcess;
public static class Program
{
public static bool Cancelled { get; set; }
#region Nested classes to support running as service
public const string ServiceName = "MyService";
public class Service : ServiceBase
{
public Service()
{
ServiceName = Program.ServiceName;
}
protected override void OnStart(string[] args)
{
Program.Start(args);
}
protected override void OnStop()
{
Program.Stop();
}
}
#endregion
static void Main(string[] args)
{
if (!Environment.UserInteractive)
// running as service
using (var service = new Service())
ServiceBase.Run(service);
else
{
// running as console app
Start(args);
Console.WriteLine("Press any key to stop...");
Console.ReadKey(true);
Stop();
}
}
private static void Start(string[] args)
{
// onstart code here
try
{
SaveMessage();
}
catch (Exception e)
{
LogError();
}
}
private static void Stop()
{
// onstop code here
DisposeAll();
}
}
答
我相信你需要从System.Configuration.Install.Installer延长
喜欢的东西
public class ServiceRegister: Installer
{
public ServiceRegister()
{
ServiceProcessInstaller serviceProcessInstaller =
new ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
#if RUNUNDERSYSTEM
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
#else
// should prompt for user on install
processInstaller.Account = ServiceAccount.User;
processInstaller.Username = null;
processInstaller.Password = null;
#endif
serviceInstaller.DisplayName = "SomeName";
serviceInstaller.StartType = ServiceStartMode.Manual;
serviceInstaller.ServiceName = "SomeName";
this.Installers.Add(serviceProcessInstaller);
this.Installers.Add(serviceInstaller);
}
}
答
我安装一个服务最喜欢的方式是使用SC
命令行实用程序。
完整的语法(吓唬大家!)
sc [<ServerName>] create [<ServiceName>] [type= {own | share | kernel | filesys | rec | interact type= {own | share}}] [start= {boot | system | auto | demand | disabled}] [error= {normal | severe | critical | ignore}] [binpath= <BinaryPathName>] [group= <LoadOrderGroup>] [tag= {yes | no}] [depend= <dependencies>] [obj= {<AccountName> | <ObjectName>}] [displayname= <DisplayName>] [password= <Password>]
简单来说,
SC create YourServiceName start= auto binPath= "path/to/your/exe" DisplayName= "Your Display Name"
删除服务,该命令是
SC delete YourServiceName
上述命令需要使用管理员权限从命令提示符运行。请注意,“=”号之后的空格很重要。
相关SO post
参见[这个问题](https://stackoverflow.com/questions/7922105/install-windows-service-created-in-visual-studio) - 虽然就个人而言,我会用[Topshelf ](https://www.nuget.org/packages/Topshelf/) - _“通过引用Topshelf,您的控制台应用程序**成为一个服务安装程序,它提供了一组全面的命令行选项,用于安装,配置和运行您的应用程序作为服务。“_ – stuartd