Executing Code During MSI Package Installation

Ever wondered if you can execute code during an installation of your Visual Studio Setup project? It can be that you want to modify the Windows registry or set up some custom directories, or simply check for something. In any case, it’s easy to do, just make sure you watch out for exceptions so that you get things logged properly and your push-to-all-users admin doesn’t come a’door screaming that it’s all your fault 🙂

Setting up code to run during the installation is easy. Just make a mental note that “before install” does not mean that your code will be executed right after the user double-clicks your msi file. Read on and then explore and experiment with the overridden methods to get your very own desired effect. 🙂

So, let’s start! Because it is an installation package, if you were to execute custom code, it will need to reside somewhere where the msi installer executable (msiexec.exe) can access it. That means you have to have it a separate class library project that can be loaded before anything else is installed.

Assuming you already got your solution going, add a new Class Library project to it and hit that sweet delete button on the by default generated Class.cs class. Add a “New Item” to this newly created class library and select “Installer Class”. This class will be loaded during the installation and will determine what and when to execute. Hopefully, you already have got a setup project for your solution. If you haven’t – add one.

Let’s go back to our Install Class – what we want to do is to override Install() method (or whatever events you choose):

public override void Install(IDictionary stateServer)
{
	MessageBox.Show("Installing!");
}

At this point, all you need to do is to have your setup project run this code during installation. Right-click on your setup project, select View and then Custom Actions. Right-click on Install and hit Add Custom Action. You may be perplexed a bit by your inability to select a file – select something from a drop-down on the top (Application Folder, for instance), and you will be able to browse by clicking Add File.

Did I mention building the solution before we do that? 🙂 You want to browse to and select the DLL that contains your installer class. Add it up and it’s going to show there under Custom Actions > Install.

You are done! Build the solution and run the msi!

This entry was posted in C# and tagged , , , , , . Bookmark the permalink.

One Response to Executing Code During MSI Package Installation

  1. Great information! I’ve been looking for something like this for a while now. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *