Search code examples
.netcsproj

How can I reliably edit the <Version> element in a .Net SDK style .csproj file?


I would like to edit the <Version> element in the .csproj file using a build script right before running MSBuild. In my first naive attempt I used regex and replaced <Version>.+?</Version> with the version I wanted to use.

One of the solutions had a .csproj file with a <PackageReference> that also had a nested <Version> element so the script updated it too which broke the build.

I plan to use an XPath query next and update the <Version> element that is nested below <PropertyGroup>.

Is this a reliable way to set the version in a build script? If not, what method is reliable?


Solution

  • If you only want to set the Version property per-build, you can edit the .csproj by hand to only have the value specified in the file be the default:

      <PropertyGroup>
        <!-- Any other tags in this PropertyGroup go here... -->
        <Version Condition="'$(Version)' == ''">1.2.3</Version>
      </PropertyGroup>
    

    Then, when calling MSBuild, you can specify a different value for the Version property, e.g.:

    msbuild /p:Version=4.5.6 YourProject.csproj