为了让人们知道他们正在使用的程序版本,我想在窗口标题中显示productversion.我可以手动执行此操作,但我希望它是动态的,因此每次版本更改时我都不必更改这两个项目.
这有可能在代码中执行此操作而不会弄乱安装程序吗?
解决方法
您可以使用以下代码从
AssemblyName.Version
属性中检索版本:
Version version = Assembly.GetExecutingAssembly().GetName().Version; this.Text = "My Cool Product - Version " + version; // or with a fancier formatting this.Text = string.Format("My Cool Product - Version {0}.{1}.{2} Revision {3}",version.Major,version.Minor,version.Build,version.Revision);
更新(评论后):
您还可以从存储在注册表中的MSI信息中读取设置的版本.这最好基于您的设置指定的UpgradeCode来完成,因为UpgradeCode不应在版本之间更改.以下示例程序演示了如何获取属于特定UpgradeCode的已安装版本1:
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; class Program { [DllImport("msi.dll",CharSet = CharSet.Unicode)] static extern Int32 MsiGetProductInfo(string product,string property,[Out] StringBuilder valueBuf,ref Int32 len); [DllImport("msi.dll",CharSet = CharSet.Auto,SetLastError = true)] static extern Int32 MsiEnumRelatedProducts(string strUpgradeCode,int reserved,int iIndex,StringBuilder sbProductCode); static void Main(string[] args) { List<string> installedVersions = GetInstalledVersions("{169C1A82-2A82-490B-8A9A-7AB7E4C7DEFE}"); foreach (var item in installedVersions) { Console.WriteLine(item); } } static List<string> GetInstalledVersions(string upgradeCode) { List<string> result = new List<string>(); StringBuilder sbProductCode = new StringBuilder(39); int iIdx = 0; while ( 0 == MsiEnumRelatedProducts(upgradeCode,iIdx++,sbProductCode)) { Int32 len = 512; StringBuilder sbVersion = new StringBuilder(len); MsiGetProductInfo(sbProductCode.ToString(),"VersionString",sbVersion,ref len); result.Add(sbVersion.ToString()); } return result; } }
1请注意,可能会并行安装一个产品的多个版本.在极少数情况下,您将获得包含所有已安装版本的列表.