Visual Studio Setup Project - Remove files created at runtime when uninstall

我的梦境 提交于 2019-12-04 05:33:56

问题


I am creating a C# .NET WinForms application and I am creating the installer as a Visual Studio setup project.

On Windows 10, I can remove the installed files in the control panel. However, during runtime my application creates a folder containing log files, and this folder and the log files are not removed when the app is uninstalled.

How can I make these files also be removed when the program is uninstalled?


回答1:


You can use a custom installer action to perform custom actions during installation or uninstalling the application. To do so, you need to add a new class library containing a class which derives from CustomAction.

To do so, follow these steps:

  1. Add a new Setup project. (If you don't have project template, download and install it from here for VS2013, VS2015 or VS2017 and VS2019)
  2. Add primary output from your main project to the setup project.
  3. Add a new class library project.
  4. Add a new installer action to the class library project and use the code at the end of these steps.
  5. Add primary output of the class library to the setup project
  6. Right click on setup project in solution explorer and in view menu, select Custom Actions.
  7. In the custom actin editor, right click on uninstall and select Add Custom Action ... and select primary output of class library.
  8. Rename the action to RemoveFiles and in properties set CustomActionData property exactly to /path="[TARGETDIR]\".
  9. Rebuild the solution and the setup project.
  10. Install the project.

Code for Custom Action

Add a reference to System.Configuration.Install assembly and then add a class to the project having following content. You can simply have any logic that you need here.

using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;

namespace InstallerActions
{
    [RunInstaller(true)]
    public partial class RemoveFiles : Installer
    {
        protected override void OnAfterUninstall(IDictionary savedState)
        {
            var path = System.IO.Path.Combine(Context.Parameters["path"], "log");
            System.IO.Directory.Delete(path, true);
        }
    }
}


来源:https://stackoverflow.com/questions/46786297/visual-studio-setup-project-remove-files-created-at-runtime-when-uninstall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!