卸载C#Windows服务 - 使用卸载程序

时间:2010-01-25 17:20:08

标签: c# windows-services

我为我的Windows服务创建了一个安装项目。 它安装得很好,但是,如果我卸载项目(通过添加/删除程序,或右键单击VS中的安装项目 - 卸载)它似乎不会删除该服务。

我必须在命令行使用sc delete来执行此操作,然后重新启动。

我说错了吗?

3 个答案:

答案 0 :(得分:2)

Installer课程中(您通过自定义操作调用),请务必覆盖UnInstall方法并致电<pathToFramework>\InstallUtil.exe /u <pathToServiceExe>以卸载服务。

答案 1 :(得分:0)

我不确定在安装程序项目中是否有一种简单的方法可以执行此操作,但这是我们在代码中执行此操作的方法。当您在命令行上传递“/ uninstall”时,我们的服务会在内部执行卸载。

public static readonly string UNINSTALL_REG_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
public static readonly string UNINSTALL_REG_GUID = "{1C2301A...YOUR GUID HERE}";

using (RegistryKey parent = Registry.LocalMachine.OpenSubKey(UNINSTALL_REG_KEY, true))
{
    try
    {
        RegistryKey key = null;

        try
        {
            key = parent.OpenSubKey(UNINSTALL_REG_GUID, true);
            if (key == null)
            {
                key = parent.CreateSubKey(UNINSTALL_REG_GUID);
            }

            Assembly asm = typeof (Service).Assembly;
            Version v = asm.GetName().Version;
            string exe = "\"" + asm.CodeBase.Substring(8).Replace("/", "\\\\") + "\"";

            key.SetValue("DisplayName", DISPLAY_NAME);
            key.SetValue("ApplicationVersion", v.ToString());
            key.SetValue("Publisher", "Company Name");
            key.SetValue("DisplayIcon", exe);
            key.SetValue("DisplayVersion", v.ToString(2));
            key.SetValue("URLInfoAbout", "http://www.company.com");
            key.SetValue("Contact", "support@company.com");
            key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
            key.SetValue("UninstallString", exe + " /uninstallprompt");
        }
        finally
        {
            if (key != null)
            {
                key.Close();
            }
        }
    }
    catch (Exception ex)
    {
        throw new Exception(
            "An error occurred writing uninstall information to the registry.  The service is fully installed but can only be uninstalled manually through the command line.",
            ex);
    }
}

答案 2 :(得分:0)

查看有关MDSN的ServiceInstaller文档。您添加一个继承自System.Configuration.Install.Installer的类,创建一个ServiceInstaller并将该ServiceInstaller添加到Installers属性中。

执行此操作后,安装程序项目应该能够为您安装和卸载。

安装程序类的示例:

/// <summary>
/// The installer class for the application
/// </summary>
[RunInstaller(true)]
public class MyInstaller : Installer
{
    /// <summary>
    /// Constructor for the installer
    /// </summary>
    public MyInstaller()
    {
        // Create the Service Installer
        ServiceInstaller myInstaller = new ServiceInstaller();
        myInstaller.DisplayName = "My Service";
        myInstaller.ServiceName = "mysvc";

        // Add the installer to the Installers property
        Installers.Add(myInstaller);
    }
}
相关问题