Wix5技术问询:如何添加自定义动作创建含安装路径的文件并传参?
Wix5 实现安装末尾创建含安装目录路径的文件
VBScript方案的修正与参数传递
你当前的问题核心是CustomActionData的使用方式错误,以及执行顺序不对,先给出修正后的可行方案:
1. 修正Wix配置
需要给自定义动作绑定专属的CustomActionData属性(而非全局的CustomActionData),同时指定VBScript的函数调用,并调整执行顺序到安装末尾:
<Fragment> <ComponentGroup Id="ExampleComponents" Directory="INSTALLFOLDER"> <ComponentGroupRef Id="Package1"/> </ComponentGroup> <Binary Id="vbsexecutionTest" SourceFile="createFile.vbs"/> <!-- 给自定义动作传递INSTALLFOLDER参数 --> <Property Id="LaunchMyApp" Value="[INSTALLFOLDER]"/> <CustomAction Id="LaunchMyApp" BinaryRef="vbsexecutionTest" VBScriptCall="CreateInstallDirFile" Execute="deferred" Return="check"/> <InstallExecuteSequence> <!-- 安装流程末尾执行,替换为InstallFinalize --> <Custom Action="LaunchMyApp" After="InstallFinalize"/> </InstallExecuteSequence> </Fragment>
2. 修正VBScript代码
延迟执行的自定义动作只能通过Session.CustomActionData获取参数,你的createFile.vbs需要编写对应的函数:
Sub CreateInstallDirFile() Dim installDir, fso, targetFile ' 获取传递的安装目录路径 installDir = Session.CustomActionData ' 创建FileSystemObject实例 Set fso = CreateObject("Scripting.FileSystemObject") ' 定义目标文件路径(安装目录下的installPath.txt) targetFile = fso.BuildPath(installDir, "installPath.txt") ' 创建文件并写入内容 With fso.CreateTextFile(targetFile, True) .WriteLine(installDir) .Close End With End Sub
更推荐的替代方案:C#自定义动作
VBScript在Windows Installer场景下存在调试困难、错误处理弱、部分受限环境禁用等问题,更推荐使用C#编写自定义动作:
1. 编写C#自定义动作
创建类库项目,通过NuGet安装WiX Toolset.Dtf.WindowsInstaller包,编写代码:
using Microsoft.Deployment.WindowsInstaller; namespace WixCustomActions { public class InstallActions { [CustomAction] public static ActionResult CreateInstallPathFile(Session session) { // 从CustomActionData中读取安装目录 string installDir = session.CustomActionData["INSTALLFOLDER"]; string targetPath = System.IO.Path.Combine(installDir, "installPath.txt"); // 写入文件内容 System.IO.File.WriteAllText(targetPath, installDir); return ActionResult.Success; } } }
2. Wix项目中配置引用
<Fragment> <ComponentGroup Id="ExampleComponents" Directory="INSTALLFOLDER"> <ComponentGroupRef Id="Package1"/> </ComponentGroup> <!-- 引用编译后的C#类库 --> <Binary Id="CustomActionsDll" SourceFile="..\WixCustomActions\bin\Release\WixCustomActions.dll"/> <!-- 定义自定义动作 --> <CustomAction Id="CreateInstallPathFile" BinaryRef="CustomActionsDll" DllEntry="CreateInstallPathFile" Execute="deferred" Return="check"/> <!-- 传递INSTALLFOLDER参数 --> <Property Id="CreateInstallPathFile" Value="INSTALLFOLDER=[INSTALLFOLDER]"/> <!-- 安装末尾执行 --> <InstallExecuteSequence> <Custom Action="CreateInstallPathFile" After="InstallFinalize"/> </InstallExecuteSequence> </Fragment>
关键注意事项
- 延迟执行的自定义动作无法直接访问Wix属性,必须通过与自定义动作同名的Property设置
CustomActionData来传递参数 - 要在安装流程末尾执行,必须将动作顺序设置为
After="InstallFinalize",这是安装过程的最后步骤 - C#自定义动作相比VBScript,稳定性更强、调试更便捷,且兼容性更好
内容的提问来源于stack exchange,提问作者Bruno C
相关产品推荐
相关产品推荐

