c#命令提示符应用程序到windows服务-如何创建安装程序类



如何将命令提示应用程序转换为windows服务?到目前为止,这就是我所拥有的,但是当我尝试使用InstallUtil.exe安装它时,我收到了一个错误:

没有带有RunInstallerAttribute的公共安装程序。是属性可以在....

中找到。

我不知道我必须创建一个安装程序类,我不知道如何去做。有人可以帮助我告诉我如何写一个安装程序类,这样我就可以安装我的应用程序作为一个windows服务?

   class Program
   {
    public const string ServiceName = "ProcessingApp";
    public class Service : ServiceBase
    {
        public Service()
        {
            ServiceName = Program.ServiceName;
        }
        protected override void OnStart(string[] args)
        {
            Program.Start(args);
        }
        protected override void OnStop()
        {
            Program.Stop();
        }
    }
    private static void Start(string[] args)
    {
        // onstart code here
        StartCode();
    }
    private static void Stop()
    {
        // onstop code here
        ServiceController service = new ServiceController(ServiceName);
        try
        {
            TimeSpan timeout = TimeSpan.FromMilliseconds(100000);
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
        }
        catch
        {
        }
    }
    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();
        }

要做到这一点,您需要在System.Configuration.Install.dll中继承System.Configuration.Install.Installer的类。构造函数应该配置一个ServiceProcessInstaller和一个ServiceInstaller,并将它们都添加到Installers集合中——设置AccountStartTypeServiceNameDescription等。

MSDN有一个例子:https://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceprocessinstaller(v=vs.110).aspx

最新更新