在Windows Server 2003中将控制台应用程序安装为Windows服务

4
这可能是一个基础问题,先提前致歉。
我有一个控制台应用程序,想在Windows Server 2003上进行测试。
我使用C#和4.0框架在发布模式下构建了该应用程序,并将bin文件夹的内容复制到Windows Server 2003目录中的一个文件夹中。
当我运行exe时,出现以下错误: “无法从命令行或调试器启动服务。必须先安装 Windows 服务(使用 installutil.exe),然后使用 ServerExplorer 启动……”
现在我想使用installutil.exe将此控制台应用程序安装为服务。
请问有人能教我如何操作吗?
谢谢。

当你运行InstallUtil时发生了什么? - nvoigt
我收到了安装确认信息。但是在组件服务中我看不到我的服务。 - Aziz Qureshi
1
你的服务不会出现在组件服务中,而是只会出现在“服务”中。开始->运行->输入Services.msc->按回车键。如果安装正确,你的服务应该在那里。 - Abhinav
当你从控制台运行应用程序时会发生什么?如果它运行并立即退出,那么当你将其安装为服务时也会发生同样的事情。服务将启动,然后立即停止,因为应用程序已经完成。它不会因为你将其安装为服务而保持运行状态。 - Joel Coehoorn
@Abhinav:我查看了Services.msc,但无法找到我的服务。我查看了日志文件,它提到了以下内容:“在<FilePath>中找不到具有RunInstallerAttribute.Yes属性的公共安装程序”。我的应用程序是作为控制台应用程序构建的,而不是Windows服务应用程序。 - Aziz Qureshi
您可以使用sc命令行工具从任何.exe文件创建服务。 - Joel Coehoorn
2个回答

5
你需要更改Main方法。
static partial class Program
{
    static void Main(string[] args)
    {
        RunAsService();
    }

    static void RunAsService()
    {
        ServiceBase[] servicesToRun;
        servicesToRun = new ServiceBase[] { new MainService() };
        ServiceBase.Run(servicesToRun);
    }
}

您需要创建一个新的Windows服务(MainService)和安装程序类(MyServiceInstaller);

MainService.cs文件:

partial class MainService : ServiceBase
{
    public MainService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
    }

    protected override void OnStop()
    {
        base.OnStop();
    }

    protected override void OnShutdown()
    {
        base.OnShutdown();
    }
}

MyServiceInstaller.cs;

[RunInstaller(true)]
public partial class SocketServiceInstaller : System.Configuration.Install.Installer
{
    private ServiceInstaller serviceInstaller;
    private ServiceProcessInstaller processInstaller;

    public SocketServiceInstaller()
    {
        InitializeComponent();

        processInstaller = new ServiceProcessInstaller();
        serviceInstaller = new ServiceInstaller();

        processInstaller.Account = ServiceAccount.LocalSystem;
        serviceInstaller.StartType = ServiceStartMode.Automatic;
        serviceInstaller.ServiceName = "My Service Name";

        var serviceDescription = "This my service";

        Installers.Add(serviceInstaller);
        Installers.Add(processInstaller);
    }
}

0
现在我想使用installutil.exe将这个控制台应用程序安装为服务。
您需要将其转换为Windows服务应用程序,而不是控制台应用程序。请参阅MSDN上的“演练:创建Windows服务”以获取详细信息。
另一个选择是使用Windows任务计划程序来安排系统运行您的控制台应用程序。这可以非常类似于服务,而不必实际创建服务,因为您可以安排应用程序在任何您选择的时间表上运行。

我猜他已经有一个服务了,否则他不会首先收到那个错误消息。 - nvoigt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接