在WPF程序标题栏中集成Git标签信息的实现问题
步骤1:定义自定义Git版本属性
在项目中新建一个类文件(比如GitVersionAttribute.cs),用来存储Git版本信息:
using System; [AttributeUsage(AttributeTargets.Assembly)] public class GitVersionAttribute : Attribute { public string Version { get; } public GitVersionAttribute(string version) { Version = version; } }
步骤2:修改项目文件,添加MSBuild自动生成版本逻辑
编辑你的WPF项目文件(.csproj),在<Project>标签内插入以下内容,实现构建时自动执行Git命令并生成版本属性代码:
<Target Name="GenerateGitVersion" BeforeTargets="CoreCompile"> <!-- 执行git describe命令获取版本,指定工作目录确保Git能识别仓库 --> <Exec Command="git describe --tags --dirty" WorkingDirectory="$(SolutionDir)" ConsoleToMSBuild="true" IgnoreExitCode="false"> <Output TaskParameter="ConsoleOutput" PropertyName="GitVersion" /> </Exec> <!-- 生成临时代码文件,写入版本属性 --> <WriteLinesToFile File="$(IntermediateOutputPath)GitVersion.Generated.cs" Lines=" using System; [assembly: GitVersionAttribute("$(GitVersion)")]" Overwrite="true" Encoding="UTF-8" /> <!-- 将生成的文件加入编译列表 --> <ItemGroup> <Compile Include="$(IntermediateOutputPath)GitVersion.Generated.cs" /> </ItemGroup> </Target>
WorkingDirectory设为$(SolutionDir)适配仓库根目录结构,若项目在子目录可改为$(ProjectDir)BeforeTargets="CoreCompile"确保编译前完成版本文件生成,保证代码能正常引用属性
步骤3:在WPF窗口中读取版本并设置标题
在主窗口的构造函数(或Loaded事件)中读取属性,更新标题栏:
using System.Reflection; public MainWindow() { InitializeComponent(); var gitVersionAttr = Assembly.GetExecutingAssembly() .GetCustomAttribute<GitVersionAttribute>(); if (gitVersionAttr != null) { Title = $"我的WPF程序 - {gitVersionAttr.Version}"; } }
针对你之前问题的说明
- 批处理预/后构建无反应:大概率是MSBuild工作目录与Git仓库不匹配,或批处理路径逻辑有问题。用MSBuild的
Exec任务可直接指定工作目录,比批处理更稳定。 - MSBuild目标设置属性:上述方法通过生成临时代码文件的方式,避免了手动修改AssemblyInfo.cs可能遇到的文件锁定、构建同步问题,无需额外依赖第三方任务库。
注意事项
- 确保开发环境已安装Git,且
git命令能在命令行正常执行 - 若在CI/CD环境构建,需确保代理能访问Git仓库,可在
Exec命令中追加git fetch --tags拉取所有标签
内容的提问来源于stack exchange,提问作者Droidling
相关产品推荐
相关产品推荐

