For SDK-style projects that are built using dotnet.exe
, assembly version attributes are generated automatically, so you can use /p:Version=5.4.3.0
right out of the box.
If you use the old project format, you need to add the following BeforeBuild
step to your .csproj
file. No need to use extra .targets
and extension packs, because MSBuild already has a nice built-in task which does most of the stuff:
<Target Name="BeforeBuild">
<ItemGroup>
<AssemblyAttributes Include="AssemblyVersion">
<_Parameter1>$(Version)</_Parameter1>
</AssemblyAttributes>
</ItemGroup>
<MakeDir Directories="$(IntermediateOutputPath)" />
<WriteCodeFragment Language="C#"
OutputFile="$(IntermediateOutputPath)Version.cs"
AssemblyAttributes="@(AssemblyAttributes)" />
<ItemGroup>
<Compile Include="$(IntermediateOutputPath)Version.cs" />
</ItemGroup>
</Target>
Just make sure you remove the existing AssemblyVersion
attribute because it will now be generated during build.
Update 7/29/2020:
Michael Parker has pointed out that if you use this approach and do a build from Visual Studio, you end up with an empty version in the Version.cs
file. To overcome this, I suggest defining the default Version value in your .csproj
or Directory.Build.props
file as follows:
<PropertyGroup>
...
<Version Condition="'$(Version)' == ''">1.0.0.0</Version>
</PropertyGroup>
This will set it to 1.0.0.0
if Version wasn't specified in the command line.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…