Windows Installer: Removing Folders


Recently I put together a Windows Installer package (MSI file) for our team to use internally.

Without you having to do any extra work, the Windows Uninstaller automatically takes care of deleting any folders where it installed content. However, if an app writes to other folders that the installer doesn’t know about, it’s your responsibility to handle the removal of those folders.

In my case, the app that I was installing writes temporary files to a cache folder. The app could cache gigabytes of data, so it was key that the uninstall remove all those temporary files. Fortunately, WiX makes this easy. Here are the steps. First, we search the registry for the location of the cache folder and store it in a Property. We’ll use this if we’re uninstalling. Replace CompanyName and AppName with your company and app names.

<?define AppRegKey = "Software\CompanyName\AppName" ?>
<Property Id="CACHEFOLDER">
 <RegistrySearch Key="$(var.AppRegKey)" Root="HKCU" Type="raw"
 Id="CacheFolderRegSearch" Name="CachePath" />
</Property>

Second, in the case we’re installing, we need to save the location of the cache folder in the registry, so that we can invoke the “RemoveFolderEx” command on that folder during a future uninstall.

<?define AppCacheFolder = "AppCache" ?>
<Component Id="CacheCleanup" Guid="*">
 <RegistryValue Root="HKCU" Key="$(var.AppRegKey)"
 Name="CachePath" Type="string" Value="[TempFolder]$(var.AppCacheFolder)" KeyPath="yes" />
 <util:RemoveFolderEx On="uninstall" Property="CACHEFOLDER"/>
</Component>

We need to reference the component we’ve registered in a Feature block, along with other relevant components.

<Feature Id="MainApplication" Title="App Name" Level="1">
 <ComponentRef Id="OtherComponents" />
 <ComponentRef Id="CacheCleanup" />
</Feature>

To make this all work correctly, there are two more steps. First, ensure your WSX source references the utility extension where util:RemoveFolderEx is located.

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns = "http://schemas.microsoft.com/wix/2006/wi"
     xmlns:util = "http://schemas.microsoft.com/wix/UtilExtension">

And second, reference the extension when you compile and link:

candle source.wxs -ext WixUtilExtension.dll
light source.wixobj -ext WixUtilExtension.dll

That’s it. Now the installation will correctly store a registry reference to the cache folder and clean up the cache folder on uninstall.

Advertisements
This entry was posted in Computers and Internet, Installers, Microsoft, WiX. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s