I had the same need and found a solution by looking at WiX's own bundle:
<Variable
Name='InstallFolder'
Type='string'
Value='[ProgramFilesFolder]WiX Toolset v$(var.WixMajorMinor)' />
<util:RegistrySearch
Id="PreviousInstallFolderSearch"
Root='HKLM'
Key='SOFTWARE\Microsoft\Windows Installer XML\$(var.WixMajorMinor)'
Value='InstallFolder'
Variable='PreviousInstallFolder' />
<util:DirectorySearch
Path='[PreviousInstallFolder]'
Variable='InstallFolder'
After='PreviousInstallFolderSearch'
Condition='PreviousInstallFolder' />
The <Variable/>
element defines the default value.
The <util:RegistrySearch/>
looks for the registry value (and, if found, saves it in a new variable called PreviousInstallFolder
).
The <util:DirectorySearch/>
executes only if the registry key was found. It checks that the directory exists and sets InstallFolder
if it does.
Note that if the registry value exists, but the directory it specifies does not exist, then the default value will be used instead.