You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在延迟模式C#自定义操作中设置MSI属性的方法

延迟模式C#自定义操作设置MSI属性的方法

延迟执行的C#自定义操作无法像即时模式那样直接通过session["PropertyName"] = "PropertyValue";修改MSI属性——这是因为延迟模式下Session对象处于受限状态,不支持写入属性操作。要实现类似效果,需通过中间存储+后续即时操作的方式完成,具体方案如下:

核心思路

延迟操作只能读取CustomActionData,无法直接修改MSI属性。因此需要:

  1. 在延迟操作中将目标值写入临时存储(如系统注册表的MSI预留路径)
  2. 添加一个即时模式的自定义操作(放在延迟操作之后),从临时存储读取值并写入目标MSI属性

具体实现代码

1. 延迟自定义操作中写入临时注册表

public static ActionResult MyDelayedCustomAction(Session session)
{
    try
    {
        // 要设置的目标属性名和值
        string targetProperty = "MY_CUSTOM_PROPERTY";
        string propertyValue = "NewPropertyValue";
        
        // 构建MSI用户数据的注册表路径(需替换ProductCode的连字符)
        string productCode = session["ProductCode"].ToString().Replace("-", "");
        string regPath = $@"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\{productCode}\InstallProperties";
        
        // 打开注册表项并写入临时值
        using (RegistryKey key = Registry.LocalMachine.OpenSubKey(regPath, true))
        {
            key?.SetValue($"{targetProperty}_TEMP", propertyValue);
        }
        
        return ActionResult.Success;
    }
    catch (Exception ex)
    {
        session.Log($"Error in delayed action: {ex.Message}");
        return ActionResult.Failure;
    }
}

2. 后续即时自定义操作中读取并设置属性

public static ActionResult MyImmediateCustomAction(Session session)
{
    try
    {
        string targetProperty = "MY_CUSTOM_PROPERTY";
        string productCode = session["ProductCode"].ToString().Replace("-", "");
        string regPath = $@"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\{productCode}\InstallProperties";
        
        using (RegistryKey key = Registry.LocalMachine.OpenSubKey(regPath, false))
        {
            if (key != null)
            {
                string tempValue = key.GetValue($"{targetProperty}_TEMP")?.ToString();
                if (!string.IsNullOrEmpty(tempValue))
                {
                    // 设置目标MSI属性
                    session[targetProperty] = tempValue;
                    // 清理临时注册表项
                    key.DeleteValue($"{targetProperty}_TEMP");
                }
            }
        }
        
        return ActionResult.Success;
    }
    catch (Exception ex)
    {
        session.Log($"Error in immediate action: {ex.Message}");
        return ActionResult.Failure;
    }
}

关键注意事项

  • 权限设置:延迟自定义操作需将Impersonate属性设为no,确保以系统权限运行,才能写入注册表。
  • 序列位置:即时操作必须放在延迟操作之后,且处于MSI序列的即时阶段(比如InstallFinalize之前)。
  • 路径安全性:使用MSI预留的UserData注册表路径,避免修改系统其他关键位置,减少权限冲突风险。

内容的提问来源于stack exchange,提问作者S_1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 12:52:25