如何通过dotnet build传递参数并在C#代码中访问以动态设置安装程序版本?
解决方案
方法1:通过MSBuild生成编译时常量
在你的.csproj文件中添加配置,将构建时传递的属性转为C#编译常量:
<PropertyGroup> <!-- 设默认值,避免未传参数时编译出错 --> <MyProp Condition="'$(MyProp)' == ''">1.0.0.0</MyProp> </PropertyGroup> <Target Name="InjectBuildPropsToConstants" BeforeTargets="CoreCompile"> <PropertyGroup> <DefineConstants>$(DefineConstants);MY_INSTALLER_VERSION="$(MyProp)"</DefineConstants> </PropertyGroup> </Target>
之后在C#代码中直接使用这个常量:
string installerVersion = MY_INSTALLER_VERSION; // 后续可直接用这个变量做版本相关逻辑
执行构建命令:
dotnet build -p:MyProp="2.3.1.0"
方法2:绑定程序集版本字段(适配安装场景)
如果你的目标是设置安装程序版本,可直接将传递的属性绑定到程序集版本,再通过代码读取程序集信息:
修改.csproj:
<PropertyGroup> <!-- 仅在传递MyProp时覆盖版本,否则用项目默认配置 --> <AssemblyVersion Condition="'$(MyProp)' != ''">$(MyProp)</AssemblyVersion> <FileVersion Condition="'$(MyProp)' != ''">$(MyProp)</FileVersion> </PropertyGroup>
C#代码中读取程序集版本:
using System.Reflection; var assembly = Assembly.GetExecutingAssembly(); var version = assembly.GetName().Version.ToString(); // 这里拿到的就是构建时传递的版本号
构建命令同上:
dotnet build -p:MyProp="2.3.1.0"
方法3:构建时生成配置文件(适配多参数场景)
若需要传递多个动态参数,可在构建阶段生成配置文件,运行时读取:
在.csproj中添加生成配置的目标:
<Target Name="GenerateBuildConfig" BeforeTargets="Build"> <WriteLinesToFile File="$(OutputPath)\build-config.json" Lines='{"InstallerVersion":"$(MyProp)"}' Overwrite="true" /> </Target>
C#代码中读取配置文件:
using System.IO; using System.Text.Json; var configPath = Path.Combine(AppContext.BaseDirectory, "build-config.json"); var configContent = File.ReadAllText(configPath); var config = JsonSerializer.Deserialize<BuildConfig>(configContent); string version = config.InstallerVersion; // 配套的实体类 public class BuildConfig { public string InstallerVersion { get; set; } }
内容的提问来源于stack exchange,提问作者Finley
相关产品推荐
相关产品推荐

