正确的卸载Windows服务的方法?

Mun*_*Mun 14 c# setup-project visual-studio-2008

我有一个使用C#构建的Windows服务,它是通过VS2008安装项目安装的,并且在卸载过程中遇到了一些问题:

卸载前不会停止服务

卸载例程运行时,会引发有关正在使用的文件的错误.单击"继续"正确完成安装程序,但该服务仍显示在列表中,因此未正确卸载.

(目前,我不得不使用sc delete servicename手动删除它).

我试图在使用以下代码卸载之前停止服务,但它似乎没有生效:

protected override void OnBeforeUninstall(IDictionary savedState)
{
   base.OnBeforeUninstall(savedState);
   ServiceController serviceController = new ServiceController(MyInstaller.ServiceName);
   serviceController.Stop();
}
Run Code Online (Sandbox Code Playgroud)

何时调用此代码,如何在卸载之前停止服务?

卸载后未删除安装文件夹

应用程序还会在执行时在其安装文件夹中创建一些文件.卸载后,安装文件夹(C:\ Program Files\MyApp)不会被删除,并且包含应用程序创建的文件,但安装程序实际安装的所有其他文件都已成功删除.

卸载过程是否可以删除安装文件夹,包括该文件夹中的所有生成文件,如果是,如何删除?

谢谢.

Mun*_*Mun 7

为了寻找这些问题答案的人的利益:

卸载前不会停止服务

还没有找到解决方案.

卸载后未删除安装文件夹

需要重写项目安装程序中的OnAfterUninstall方法,并且必须删除任何创建的文件.如果此步骤后不包含任何文件,则会自动删除应用程序安装程序文件夹.

protected override void OnAfterUninstall(IDictionary savedState)
{
    base.OnAfterUninstall(savedState);

    string targetDir = Context.Parameters["TargetDir"]; // Must be passed in as a parameter

    if (targetDir.EndsWith("|"))
        targetDir = targetDir.Substring(0, targetDir.Length-1);

    if (!targetDir.EndsWith("\\"))
        targetDir += "\\";

    if (!Directory.Exists(targetDir))
    {
        Debug.WriteLine("Target dir does not exist: " + targetDir);
        return;
    }

    string[] files = new[] { "File1.txt", "File2.tmp", "File3.doc" };
    string[] dirs  = new[] { "Logs", "Temp" };

    foreach (string f in files)
    {
        string path = Path.Combine(targetDir, f);

        if (File.Exists(path))
            File.Delete(path);
    }

    foreach (string d in dirs)
    {
        string path = Path.Combine(targetDir, d);

        if (Directory.Exists(d))
            Directory.Delete(d, true);
    }

    // At this point, all generated files and directories must be deleted.
    // The installation folder will be removed automatically.
}
Run Code Online (Sandbox Code Playgroud)

请记住,安装文件夹必须作为参数传入:

  • 右键单击您的安装项目,然后选择View - > Custom Actions
  • 自定义操作将在主窗口中打开.右键单击Uninstall节点下的"XXX的主输出",然后选择"属性窗口"
  • 在属性窗口,CustomActionData下,输入以下内容:/ TARGETDIR = "[TARGETDIR] |" (注意最后的管道,不要删除它).

这将通过安装文件夹作为参数传递给您的卸载例程,让你知道安装的应用程序,其中,可以删除生成的文件和文件夹.