简体   繁体   English

如何使用Visual Studio为.net Windows服务创建安装程序

[英]How to create an installer for a .net Windows Service using Visual Studio

如何为使用Visual Studio创建的Windows服务创建安装程序?

In the service project do the following: 在服务项目中执行以下操作:

  1. In the solution explorer double click your services .cs file. 在解决方案资源管理器中,双击您的服务.cs文件。 It should bring up a screen that is all gray and talks about dragging stuff from the toolbox. 它应该显示一个全灰色的屏幕,并讨论从工具箱中拖动内容。
  2. Then right click on the gray area and select add installer. 然后右键单击灰色区域并选择添加安装程序。 This will add an installer project file to your project. 这会将安装程序项目文件添加到项目中。
  3. Then you will have 2 components on the design view of the ProjectInstaller.cs (serviceProcessInstaller1 and serviceInstaller1). 然后,您将在ProjectInstaller.cs(serviceProcessInstaller1和serviceInstaller1)的设计视图中拥有2个组件。 You should then setup the properties as you need such as service name and user that it should run as. 然后,您应该根据需要设置属性,例如服务名称和应该运行的用户。

Now you need to make a setup project. 现在你需要进行一个安装项目。 The best thing to do is use the setup wizard. 最好的办法是使用设置向导。

  1. Right click on your solution and add a new project: Add > New Project > Setup and Deployment Projects > Setup Wizard 右键单击您的解决方案并添加一个新项目:添加>新建项目>设置和部署项目>设置向导

    a. 一个。 This could vary slightly for different versions of Visual Studio. 对于不同版本的Visual Studio,这可能略有不同。 b. Visual Studio 2010 it is located in: Install Templates > Other Project Types > Setup and Deployment > Visual Studio Installer Visual Studio 2010位于:安装模板>其他项目类型>设置和部署> Visual Studio Installer

  2. On the second step select "Create a Setup for a Windows Application." 在第二步选择“为Windows应用程序创建安装程序”。

  3. On the 3rd step, select "Primary output from..." 在第3步,选择“主要输出...”
  4. Click through to Finish. 单击“完成”。

Next edit your installer to make sure the correct output is included. 接下来编辑安装程序以确保包含正确的输出。

  1. Right click on the setup project in your Solution Explorer. 右键单击解决方案资源管理器中的安装项目。
  2. Select View > Custom Actions. 选择查看>自定义操作。 (In VS2008 it might be View > Editor > Custom Actions) (在VS2008中,它可能是视图>编辑器>自定义操作)
  3. Right-click on the Install action in the Custom Actions tree and select 'Add Custom Action...' 右键单击“自定义操作”树中的“安装”操作,然后选择“添加自定义操作...”
  4. In the "Select Item in Project" dialog, select Application Folder and click OK. 在“在项目中选择项目”对话框中,选择“应用程序文件夹”并单击“确定”
  5. Click OK to select "Primary output from..." option. 单击“确定”以选择“主输出...”选项。 A new node should be created. 应该创建一个新节点。
  6. Repeat steps 4 - 5 for commit, rollback and uninstall actions. 对提交,回滚和卸载操作重复步骤4 - 5。

You can edit the installer output name by right clicking the Installer project in your solution and select Properties. 您可以通过右键单击解决方案中的Installer项目来编辑安装程序输出名称,然后选择“属性”。 Change the 'Output file name:' to whatever you want. 将“输出文件名:”更改为您想要的任何内容。 By selecting the installer project as well and looking at the properties windows, you can edit the Product Name , Title , Manufacturer , etc... 通过选择安装程序项目并查看属性窗口,您可以编辑Product NameTitleManufacturer等...

Next build your installer and it will produce an MSI and a setup.exe. 接下来构建安装程序,它将生成一个MSI和一个setup.exe。 Choose whichever you want to use to deploy your service. 选择要用于部署服务的任何一种。

I follow Kelsey's first set of steps to add the installer classes to my service project, but instead of creating an MSI or setup.exe installer I make the service self installing/uninstalling. 我按照Kelsey的第一组步骤将安装程序类添加到我的服务项目中,但是我没有创建MSI或setup.exe安装程序,而是让服务自行安装/卸载。 Here's a bit of sample code from one of my services you can use as a starting point. 这里有一些我可以用作起点的服务的示例代码。

public static int Main(string[] args)
{
    if (System.Environment.UserInteractive)
    {
        // we only care about the first two characters
        string arg = args[0].ToLowerInvariant().Substring(0, 2);

        switch (arg)
        {
            case "/i":  // install
                return InstallService();

            case "/u":  // uninstall
                return UninstallService();

            default:  // unknown option
                Console.WriteLine("Argument not recognized: {0}", args[0]);
                Console.WriteLine(string.Empty);
                DisplayUsage();
                return 1;
        }
    }
    else
    {
        // run as a standard service as we weren't started by a user
        ServiceBase.Run(new CSMessageQueueService());
    }

    return 0;
}

private static int InstallService()
{
    var service = new MyService();

    try
    {
        // perform specific install steps for our queue service.
        service.InstallService();

        // install the service with the Windows Service Control Manager (SCM)
        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
    }
    catch (Exception ex)
    {
        if (ex.InnerException != null && ex.InnerException.GetType() == typeof(Win32Exception))
        {
            Win32Exception wex = (Win32Exception)ex.InnerException;
            Console.WriteLine("Error(0x{0:X}): Service already installed!", wex.ErrorCode);
            return wex.ErrorCode;
        }
        else
        {
            Console.WriteLine(ex.ToString());
            return -1;
        }
    }

    return 0;
}

private static int UninstallService()
{
    var service = new MyQueueService();

    try
    {
        // perform specific uninstall steps for our queue service
        service.UninstallService();

        // uninstall the service from the Windows Service Control Manager (SCM)
        ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
    }
    catch (Exception ex)
    {
        if (ex.InnerException.GetType() == typeof(Win32Exception))
        {
            Win32Exception wex = (Win32Exception)ex.InnerException;
            Console.WriteLine("Error(0x{0:X}): Service not installed!", wex.ErrorCode);
            return wex.ErrorCode;
        }
        else
        {
            Console.WriteLine(ex.ToString());
            return -1;
        }
    }

    return 0;
}

Nor Kelsey, nor Brendan solutions does not works for me in Visual Studio 2015 Community. Nor Kelsey和Brendan解决方案在Visual Studio 2015社区中对我不起作用。

Here is my brief steps how to create service with installer: 以下是我使用安装程序创建服务的简要步骤:

  1. Run Visual Studio, Go to File -> New -> Project 运行Visual Studio,转到文件 -> 新建 -> 项目
  2. Select .NET Framework 4, in 'Search Installed Templates' type 'Service' 选择“.NET Framework 4”,在“搜索已安装的模板”中键入“服务”
  3. Select 'Windows Service'. 选择“Windows服务”。 Type Name and Location. 输入名称和位置。 Press OK . 确定
  4. Double click Service1.cs, right click in designer and select 'Add Installer' 双击Service1.cs,右键单击设计器并选择“添加安装程序”
  5. Double click ProjectInstaller.cs. 双击ProjectInstaller.cs。 For serviceProcessInstaller1 open Properties tab and change 'Account' property value to 'LocalService'. 对于serviceProcessInstaller1,打开“属性”选项卡,将“帐户”属性值更改为“LocalService”。 For serviceInstaller1 change 'ServiceName' and set 'StartType' to 'Automatic'. 对于serviceInstaller1,更改“ServiceName”并将“StartType”设置为“Automatic”。
  6. Double click serviceInstaller1. 双击serviceInstaller1。 Visual Studio creates serviceInstaller1_AfterInstall event. Visual Studio创建serviceInstaller1_AfterInstall事件。 Write code: 编写代码:

     private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e) { using (System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName)) { sc.Start(); } } 
  7. Build solution. 构建解决方案 Right click on project and select 'Open Folder in File Explorer'. 右键单击项目,然后选择“在文件资源管理器中打开文件夹”。 Go to bin\\Debug . 转到bin \\ Debug

  8. Create install.bat with below script: 使用以下脚本创建install.bat:

     ::::::::::::::::::::::::::::::::::::::::: :: Automatically check & get admin rights ::::::::::::::::::::::::::::::::::::::::: @echo off CLS ECHO. ECHO ============================= ECHO Running Admin shell ECHO ============================= :checkPrivileges NET FILE 1>NUL 2>NUL if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges ) :getPrivileges if '%1'=='ELEV' (shift & goto gotPrivileges) ECHO. ECHO ************************************** ECHO Invoking UAC for Privilege Escalation ECHO ************************************** setlocal DisableDelayedExpansion set "batchPath=%~0" setlocal EnableDelayedExpansion ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\\OEgetPrivileges.vbs" ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\\OEgetPrivileges.vbs" "%temp%\\OEgetPrivileges.vbs" exit /B :gotPrivileges :::::::::::::::::::::::::::: :START :::::::::::::::::::::::::::: setlocal & pushd . cd /d %~dp0 %windir%\\Microsoft.NET\\Framework\\v4.0.30319\\InstallUtil /i "WindowsService1.exe" pause 
  9. Create uninstall.bat file (change in pen-ult line /i to /u ) 创建uninstall.bat文件(将pen-ult行/i更改为/u
  10. To install and start service run install.bat, to stop and uninstall run uninstall.bat 要安装并启动服务,请运行install.bat,以停止和卸载运行uninstall.bat

For VS2017 you will need to add the "Microsoft Visual Studio 2017 Installer Projects" VS extension. 对于VS2017,您需要添加“Microsoft Visual Studio 2017安装程序项目”VS扩展。 This will give you additional Visual Studio Installer project templates. 这将为您提供其他Visual Studio Installer项目模板。 https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.MicrosoftVisualStudio2017InstallerProjects#overview https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.MicrosoftVisualStudio2017InstallerProjects#overview

To install the windows service you can add a new setup wizard type project and follow the steps from Kelsey's answer https://stackoverflow.com/a/9021107/1040040 要安装Windows服务,您可以添加新的安装向导类型项目,并按照Kelsey的答案中的步骤进行操作https://stackoverflow.com/a/9021107/1040040

InstallUtil classes ( ServiceInstaller ) are considered an anti-pattern by the Windows Installer community. Windows安装程序社区将InstallUtil类(ServiceInstaller)视为反模式。 It's a fragile, out of process, reinventing of the wheel that ignores the fact that Windows Installer has built-in support for Services. 这是一个脆弱的,无处理的,重新发明轮子,忽略了Windows Installer内置的服务支持这一事实。

Visual Studio deployment projects ( also not highly regarded and deprecated in the next release of Visual Studio ) do not have native support for services. Visual Studio部署项目(在Visual Studio的下一版本中也未得到高度重视和弃用)没有对服务的本机支持。 But they can consume merge modules. 但是他们可以使用合并模块。 So I would take a look at this blog article to understand how to create a merge module using Windows Installer XML that can express the service and then consume that merge module in your VDPROJ solution. 所以我将看一下这篇博客文章,了解如何使用可以表达服务的Windows Installer XML创建合并模块,然后在VDPROJ解决方案中使用该合并模块。

Augmenting InstallShield using Windows Installer XML - Windows Services 使用Windows Installer XML扩充InstallShield - Windows服务

IsWiX Windows Service Tutorial IsWiX Windows服务教程

IsWiX Windows Service Video IsWiX Windows服务视频

I know this is an old thread, but I just wanted to add my 2 cents. 我知道这是一个老线程,但我只想加2美分。 I've always hated the way you manage a service project in VS. 我一直很讨厌你在VS中管理服务项目的方式。 This is why I've used Topshelf for many years now. 这就是我多年来使用Topshelf的原因。 Take a step back, don't create a service project but a console project instead, then add Topshelf to it. 退后一步,不要创建服务项目而是创建一个控制台项目,然后将Topshelf添加到它。 It's scary easy. 这太可怕了。

https://github.com/Topshelf/Topshelf https://github.com/Topshelf/Topshelf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Visual Studio 安装程序项目安装 .NET 6 Windows 服务(Worker Service)? - How do you install a .NET 6 Windows Service (Worker Service) using a Visual Studio Installer project? 如何使用 Visual Studio 代码为 .NET Core 的工作人员服务创建安装程序 - How to create an installer for worker service of .NET Core using visual studio code 将参数发送到Windows Service Installer Visual Studio - Send parameters to Windows Service Installer Visual Studio 在 Visual Studio 2022 上为 windows 服务创建安装程序 - Creating an installer for a windows service on Visual Studio 2022 如何在 Visual Studio 中创建 MSI 安装程序? - How to Create an MSI Installer in Visual Studio? 如果由 Visual Studio 安装程序安装,则无法调试 Windows 服务 - Can't debug Windows Service if it's installed by Visual Studio Installer 使用 Visual Studio 安装程序项目将 ASP .NET 核心服务安装到 IIS - Installing ASP .NET Core service to IIS using Visual Studio Installer Projects 在 iOS 上为 .NET Maui 应用程序创建安装程序 - Visual Studio - Create installer for .NET Maui app on iOS - Visual Studio 如何在没有Visual Studio的情况下使用ASP.NET WebAPI创建RESTful Web服务? - How to create RESTful web service using ASP.NET WebAPI without Visual Studio? 如何使用WSDL文件在Visual Studio.NET中创建Web服务? - How do I create a Web Service in Visual Studio.NET using a WSDL file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM