Search code examples
c#installationwixwixsharp

C# WiX Custom Actions crash with "Could not load file or assembly"


I have a C# WiX project, like this (trimmed code):
C# WiX project Main:

public class WixInstaller
{
    public static void Main()
    {
        // Setup Project
        var project = new Project(AppName,
            // Application Dir
            new Dir(@$"%ProgramFiles%\{AppName}",
                // Application Files
                new Files($@"{binPath}\*.*"),
                // Program Menu Exe
                new File($@"{binPath}\{AppName}.exe",
                    new FileShortcut(AppName, @$"%ProgramMenu%\{AppName}") { IconFile = iconPath }))
        );

        // Run After Install
        var runAfterInstallAction = new ElevatedManagedAction(
            CustomActions.RunAfterInstall, Return.check, When.After, Step.InstallFinalize, Condition.NOT_Installed) 
        { 
            Execute = Execute.immediate 
        };
        project.AddAction(runAfterInstallAction);

        Compiler.BuildMsi(project, System.IO.Path.Combine(_solutionDirectory, fileName));
    }
}

The custom action:

public class CustomActions
{
    [CustomAction]
    public static ActionResult RunAfterInstall(Session session)
    {
        try
        {
            // This pattern in necessary to catch exceptions relating to missing dlls.
            Action(session);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }

        return ActionResult.Success;

        static void Action(Session session)
        {
            using Microsoft.Win32.TaskScheduler.TaskService ts = new();
        }
    }
}

When the custom action is executed, it errors out in Could not load file or assembly Microsoft.Win32.TaskScheduler version..... I am not sure how to fix this. There's a lot of guides available online, but seems like there's nothing on a WiX C# project, even on WiX's actual documentation. Seems like I need to add a dll file referenced by the action, but the C# project doesn't seem to have similar functionality.

  • I tried project.AddBinary(), but it didn't fix the issue.
  • I tried setting the custom action's actionAssembly to the required binary with no luck (couldn't find it, seems like no CA file was being created)
  • Making a separate project for customActions.

Solution

  • The following worked, added in the main:

    project.DefaultRefAssemblies.Add(@".\Microsoft.Win32.TaskScheduler.dll");
    

    Discussion: https://github.com/oleg-shilo/wixsharp/issues/1447