Reviewing the Install/Uninstall process I’ve created using the standard Visual Studio Setup Project template, I’ve noticed that some files were always left on the installation folder after a complete program uninstall sequence.

The default behavior is to leave on the file system any file you didn’t explicitly added to the setup solution; so if you create temp files, configuration files or whatever you might need during the program execution, they will be left on the disk.

To get rid of them I’ve wrote this extremely simple custom action:

[RunInstaller(true)]
public partial class DeleteFilesCustomAction : Installer
{
	public DeleteFilesCustomAction()
	{
		InitializeComponent();
	}

	public override void Uninstall(IDictionary savedState)
	{
		base.Uninstall(savedState);
		try
		{
			// delete any addictional files (or comepletely remove the folder)
			string pathtodelete = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
			// MessageBox.Show("Deleting: " + pathtodelete);
			if (pathtodelete != null && Directory.Exists(pathtodelete))
			{
				// delete all the file inside this folder except SID.SetupSupport
				foreach (var file in Directory.GetFiles(pathtodelete))
				{
					// MessageBox.Show(file);
					if (!file.Contains(System.Reflection.Assembly.GetAssembly(typeof (DeleteFilesCustomAction)).GetName().Name))
						SafeDeleteFile(file);
				}
				foreach (var directory in Directory.GetDirectories(pathtodelete))
					SafeDeleteDirectory(directory);
			}
		}
		catch
		{
		}
	}

	private static void SafeDeleteFile(string file)
	{
		try
		{
			File.Delete(file);
		}
		catch
		{
		}
	}

	private static void SafeDeleteDirectory(string directory)
	{
		try
		{
			Directory.Delete(directory, true);
		}
		catch (Exception)
		{
		}
	}
}

You can use it just adding the custom action to an assembly you will also add to the setup project (right click, add...new project output...and point to the project that contains your custom actions); then in the Custom Actions Editor, add the specific action under the Uninstall section.

Related Content