如何使用C#不启动安装程序、不用Orca向MSI的Property表添加新行
C# 编辑MSI文件Property表实现方案
依赖引入
- 项目中通过NuGet安装
Microsoft.Deployment.WindowsInstaller包即可,这个是微软官方封装的Windows Installer API托管实现,仅操作MSI文件本身,不会触发安装流程,也不需要依赖Orca工具。
核心实现代码
using Microsoft.Deployment.WindowsInstaller; using System; public static class MsiPropertyEditor { /// <summary> /// 新增或更新MSI文件Property表的属性值 /// </summary> /// <param name="msiFilePath">MSI文件的完整路径</param> /// <param name="propertyName">要修改的属性名</param> /// <param name="propertyValue">要设置的属性值</param> public static void SetMsiProperty(string msiFilePath, string propertyName, string propertyValue) { // 以事务模式打开MSI数据库,修改后可提交或回滚 using (var msiDb = new Database(msiFilePath, DatabaseOpenMode.Transact)) { try { // 转义值中的单引号,避免查询语法错误 string escapedValue = propertyValue.Replace("'", "''"); // 先查询属性是否存在 using (var checkView = msiDb.OpenView($"SELECT `Value` FROM `Property` WHERE `Property` = '{propertyName}'")) { checkView.Execute(); var existingRecord = checkView.Fetch(); if (existingRecord != null) { // 属性已存在,执行更新 msiDb.Execute($"UPDATE `Property` SET `Value` = '{escapedValue}' WHERE `Property` = '{propertyName}'"); } else { // 属性不存在,执行插入 msiDb.Execute($"INSERT INTO `Property` (`Property`, `Value`) VALUES ('{propertyName}', '{escapedValue}')"); } } // 提交所有修改 msiDb.Commit(); } catch { // 操作异常时回滚,避免MSI文件损坏 msiDb.Rollback(); throw; } } } // 调用示例 public static void Main() { // 替换为你的MSI文件实际路径 string targetMsiPath = @"C:\Users\xxx\Desktop\test.msi"; SetMsiProperty(targetMsiPath, "ServerUrl", "www.google.com"); } }
注意事项
- 操作MSI前建议先备份原文件,避免误操作导致文件损坏
- 如果原MSI带有数字签名,修改后签名会失效,需要重新对MSI进行签名
- 整个操作仅对MSI文件进行读写,不会触发安装程序运行,满足要求
内容的提问来源于stack exchange,提问作者alohamora
相关产品推荐
相关产品推荐

