When discussing about dynamic linked libraries, many think that you can only use C/C++ to create suitable ones for the Windows Installer, however, this is not the case. With the help of WIX Toolset, creating C# dlls for custom actions was never easier, and let’s see how we can achieve this.
Let’s start with what is needed in order to create C# DLLs for the Windows Installer. This article is intended for Visual Studio 2019, if you are using older versions of Visual Studio you can check this article.
Now that the WIX Toolset extension for Visual Studio is installed, open up Visual Studio and you will see that under Languages, a new one called WiX has been added. Select WiX and then search for C# Custom Action Project for WiX v3.
After you selected it, click on Next and give it a Project Name and select the desired Framework. For this example I ain’t going to do something crazy, so I’m going to leave .Net Framework 3.5.
Write the code
After the project is created, you will notice in the .cs file that the Microsoft.Deployment.WindowsInstaller namespace is automatically added. This is the class which offers access to all the Windows Installer APIs. A full diagram for it can be found here.
For this example, I only went and created some registry keys, and the code looks as following:
After we finish with the code, we go to Build > Build Solution, or CTRL+SHIFT+B. And voila, our DLL is created:
Add Custom Action in MSI
Once we have our DLL created, we are going to open Advanced Installer and navigate to the Custom Actions Page. Once here, search for Call function from attached native DLL and click Add custom action with sequence.
Then, in the Attached DLL field, browse to the previously created DLL file. Remember I said that the method (function) we used in Visual Studio is important? This is where we tell Advanced Installer which function to use when our DLL is executed, so in the Function field write your method (function) name.
In terms of custom action configuration, I’ve used the Execution to be When the system is being modified, and the Execution Stage Condition field I set it to NOT Installed OR REINSTALL so that the action is executed during installation and repair of the MSI, but these options depend on what you want to achieve with your Custom Action.
As a final step, install the MSI and see if your custom action performs as desired: