如何编写自定义 C# 或 VB 安装操作类来执行复杂逻辑?

解读

在国内 Windows 桌面项目交付流程中,安装包不仅要把文件拷到目标机,还要写注册表、启 Windows 服务、建数据库、配置防火墙、做环境检查、回滚脏数据等。Visual Studio 自带的“安装项目”或 InstallShield Limited 只能覆盖 70 % 场景,剩余 30 % 的“复杂逻辑”必须通过自定义操作(Custom Action)完成。
面试时,考官想确认四点:

  1. 是否知道 Custom Action 的挂载点(Install、Commit、Rollback、Uninstall)。
  2. 是否会把业务代码与安装程序解耦,写成独立的 Installer 类库,而不是把脚本直接塞进 MSI。
  3. 是否掌握状态回滚与日志规范,避免“装到一半失败却留下垃圾”。
  4. 是否能在 VB 语境下给出可编译、可调试、可本地化的完整代码骨架,而不是只讲理论。

知识点

  1. System.Configuration.Install.Installer 基类与 Install、Commit、Rollback、Uninstall 虚方法。
  2. Visual Studio “Setup Project” → Custom Actions 视图 → 添加“主输出”并设定 CustomActionData。
  3. CustomActionData 的 key=value 语法及 Context.Parameters 解析。
  4. 事务回滚:IDictionary savedState 参数、Rollback 方法内逆向清理。
  5. 日志规范:Context.LogMessage 或手动写 %TEMP%\MySetup_YYYY-MM-DD.log。
  6. 权限提升:msi 的 Privileged 属性、自定义操作里检测管理员令牌。
  7. 多语言:ResourceManager 读取 .resx,安装包根据 OS 语言自动切换。
  8. 调试技巧:msiexec /i MySetup.msi /l*v install.log + Debugger.Launch()。
  9. 与 C# 混用:VB 项目引用 C# 类库无 COM 开销,但须保持 4 个方法签名一致。
  10. 国内常见坑:360 杀毒拦截、中文路径乱码、GPO 禁止写 HKLM、Win11 强制数字签名。

答案

下面给出一份可直接放进 Visual Studio 2022、.NET Framework 4.8、VB 安装类库项目的完整示例。该示例完成“写注册表→建数据库→启服务→失败回滚”的闭环,并附带日志与本地化。

  1. 新建项目:Visual Basic → 类库(.NET Framework),命名 MySetupLibrary。
  2. 添加引用:System.Configuration.Install。
  3. 新建模块 CustomAction.vb,代码如下:
Imports System.ComponentModel
Imports System.Configuration.Install
Imports System.Data.SqlClient
Imports System.IO
Imports System.Resources
Imports System.Threading

<RunInstaller(True)>
Public Class MyCustomInstaller
    Inherits Installer

    Private _res As ResourceManager
    Private _logFile As String

    Public Sub New()
        _res = New ResourceManager("MySetupLibrary.Resources", GetType(MyCustomInstaller).Assembly)
        _logFile = Path.Combine(Path.GetTempPath(), String.Format("MySetup_{0:yyyyMMdd}.log", DateTime.Now))
    End Sub

    '入口统一写日志
    Private Sub Log(msg As String)
        Dim txt = String.Format("[{0:HH:mm:ss.fff}] {1}", DateTime.Now, msg)
        Context.LogMessage(txt)               'MSI 日志
        File.AppendAllText(_logFile, txt & vbCrLf)
    End Sub

    '安装阶段
    Public Overrides Sub Install(stateSaver As IDictionary)
        MyBase.Install(stateSaver)
        Log(_res.GetString("StartInstall"))

        '1. 解析参数
        Dim targetDir = Context.Parameters("TARGETDIR")
        If String.IsNullOrEmpty(targetDir) Then Throw New InstallException("TARGETDIR 缺失")
        Log("TARGETDIR=" & targetDir)

        '2. 写注册表
        Dim regPath = "Software\MyCompany\MyApp"
        Microsoft.Win32.Registry.LocalMachine.CreateSubKey(regPath).SetValue("Path", targetDir)
        stateSaver("RegPath") = regPath        '记录到状态,供回滚

        '3. 建数据库
        Dim connStr = Context.Parameters("CONNSTR")
        If String.IsNullOrEmpty(connStr) Then Throw New InstallException("CONNSTR 缺失")
        Using conn = New SqlConnection(connStr)
            conn.Open()
            Dim sql = "IF NOT EXISTS (SELECT * FROM sys.databases WHERE name='MyAppDB') CREATE DATABASE MyAppDB"
            Using cmd = New SqlCommand(sql, conn)
                cmd.ExecuteNonQuery()
            End Using
        End Using
        stateSaver("CreatedDB") = True

        '4. 启服务
        Dim svcName = Context.Parameters("SERVICENAME")
        If Not String.IsNullOrEmpty(svcName) Then
            Dim sc = New ServiceController(svcName)
            If sc.Status <> ServiceControllerStatus.Running Then
                sc.Start()
                sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30))
            End If
            stateSaver("StartedService") = True
        End If

        Log(_res.GetString("InstallOK"))
    End Sub

    '提交阶段
    Public Overrides Sub Commit(savedState As IDictionary)
        MyBase.Commit(savedState)
        Log("Commit 完成,安装事务已提交")
    End Sub

    '回滚阶段
    Public Overrides Sub Rollback(savedState As IDictionary)
        Log("开始回滚")
        If savedState Is Nothing Then Return

        '1. 删库
        If TypeOf savedState("CreatedDB") Is Boolean Then
            Try
                Dim connStr = Context.Parameters("CONNSTR")
                Using conn = New SqlConnection(connStr)
                    conn.Open()
                    Dim sql = "IF EXISTS (SELECT * FROM sys.databases WHERE name='MyAppDB') DROP DATABASE MyAppDB"
                    Using cmd = New SqlCommand(sql, conn)
                        cmd.ExecuteNonQuery()
                    End Using
                End Using
            Catch ex As Exception
                Log("回滚删库失败:" & ex.Message)
            End Try
        End If

        '2. 停服务
        If TypeOf savedState("StartedService") Is Boolean Then
            Try
                Dim svcName = Context.Parameters("SERVICENAME")
                Dim sc = New ServiceController(svcName)
                If sc.Status = ServiceControllerStatus.Running Then
                    sc.Stop()
                    sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30))
                End If
            Catch ex As Exception
                Log("回滚停服务失败:" & ex.Message)
            End Try
        End If

        '3. 删注册表
        If savedState.Contains("RegPath") Then
            Try
                Microsoft.Win32.Registry.LocalMachine.DeleteSubKeyTree(CStr(savedState("RegPath")), False)
            Catch ex As Exception
                Log("回滚删注册表失败:" & ex.Message)
            End Try
        End If

        MyBase.Rollback(savedState)
        Log("回滚完成")
    End Sub

    '卸载阶段
    Public Overrides Sub Uninstall(savedState As IDictionary)
        Log("开始卸载")
        '复用 Rollback 逻辑即可
        Rollback(savedState)
        MyBase.Uninstall(savedState)
        Log("卸载完成")
    End Sub
End Class
  1. 在 Setup Project 里:
    a. Custom Actions → Install → 添加“主输出”→ 选中 MySetupLibrary.dll。
    b. 设置 CustomActionData:
    /TARGETDIR="[TARGETDIR]\" /CONNSTR="[CONNSTR]" /SERVICENAME="MyAppService"
    c. 同样把同一主输出挂到 Commit、Rollback、Uninstall。
  2. 生成 MSI 后,用管理员命令行验证:
    msiexec /i MySetup.msi /l*v install.log
    若故意给错连接串,可观察到事务回滚、数据库被删、注册表被清,日志完整。

拓展思考

  1. 如果安装包需要支持 Win11 的“MSIX”格式,可将同一 Installer 类封装为 Windows Runtime Component,通过 Desktop Bridge 的 Package.appxmanifest 声明 desktop6:CustomAction,实现新旧格式复用。
  2. 对国内政府客户,常要求“安装过程零管理员干预”,可预置本地数据库 MDF 文件,改用 AttachDbFilename 方式,避免 CREATE DATABASE 权限问题。
  3. 当产品迭代频繁,可把复杂逻辑抽成独立的小版本 DLL,安装包仅负责拷贝与注册,业务升级通过“后台服务自更新”完成,降低 MSI 重打包频率。
  4. 若团队以 C# 为主,VB 仅负责安装脚本,可用 Shared Project 或 SDK 风格项目做多目标编译,保持单一代码基线,减少维护成本。