Search code examples
c#visual-studiomsbuildmsbuild-task

Set AssemblyInformationalVersion in AssemblyInfo.cs over msbuild Parameters


im looking for a way to do the following things:

CommandLine

msbuild myProject.csproj /p:MyInfoText

And in my C# Project in the AssemblyInfo.cs I would do:

[assembly: AssemblyInformationalVersion($MyInfoText)]

I tried targets with BeforeBuild option, but nothing worked. Anybody can and want to help?

Greetings


Solution

  • First of all thx for your comments and answers!

    I was looking for a way to set my AssemblyInformationalVersion with a property which I can set over the msbuild cli tools.

    I dont want to use any nuggets or third party libaries. So the Community.Tasks are not an option. Obivously I found a solution with this nugget for my problem.

    Now to my final solution:

    I was looking hows the Community.Task.Nugget is working and built my own solution You can declare inline Tasks in your csproj where you can write C# Code in it.

     <UsingTask TaskName="MyCustomTask" TaskFactory="CodeTaskFactory" 
            AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll"> //When using .NETCORE use here ...Tasks.Core.dll and change TaskFactory to RoslynTaskFacotry
           <ParameterGroup>
             <MyParam ParameterType="System.String" Required="true" />
           </ParameterGroup>
           <Task>
             <Reference Include="System.Core" />
             <Using Namespace="System" />
             <Code Type="Fragment" Language="cs">
               <![CDATA[
                 // My C# Code comes here!
                 // You can use your params here with Name like Console.WriteLine(MyParam)
                ]]>
             </Code>
           </Task>
         </UsingTask>
    
    

    Now you can use it like a normal Task in your .csproj

    <Target Name="foo">
     <MyCustomTask MyParamter="Test" />
    </Target>
    

    I solved my problem with coding a custom Task which can add/replace the AssemblyInformationalVersion inside the AssemblyInfo.cs before the build.