I am trying to use the WriteCodeFragment
MSBuild task to create an AssemblyVersion
attribute. I'm having a problem creating a property group to correctly pass the ITaskItem
array required for processing. Can someone help with an example?
Asked
Active
Viewed 3,989 times
5

janw
- 8,758
- 11
- 40
- 62

Timur Fanshteyn
- 2,266
- 2
- 23
- 27
1 Answers
17
This creates a file called BuildVersion.cs
with an AssemblyVersion
attribute of 123.123.123.123
. If OutputFile
is removed then a randomly generated file name will be used instead. The Compile
item name automatically adds the item to the Compile items (includes BuildVersion.cs
in the build). The FileWrites
item name allows the file to be removed during Clean.
<Target Name="BeforeBuild">
<ItemGroup>
<AssemblyAttributes Include="AssemblyVersion">
<_Parameter1>123.123.123.123</_Parameter1>
</AssemblyAttributes>
</ItemGroup>
<WriteCodeFragment AssemblyAttributes="@(AssemblyAttributes)"
Language="C#"
OutputDirectory="$(IntermediateOutputPath)"
OutputFile="BuildVersion.cs">
<Output TaskParameter="OutputFile" ItemName="Compile" />
<Output TaskParameter="OutputFile" ItemName="FileWrites" />
</WriteCodeFragment>
</Target>

sclarke81
- 1,739
- 1
- 18
- 23

Timur Fanshteyn
- 2,266
- 2
- 23
- 27
-
Thanks, this helped me. It's worth noting also that you need to add BuildVersion.cs to the Compile item as well. `
` – Josh Jan 11 '11 at 20:51 -
I've updated the code to automatically add the output to the Compile items. – bricelam Jun 16 '16 at 16:51
-
In a C# project, adding `Output TaskParameter="OutputFile" ItemName="FileWrites" />` to the content of the `WriteCodeFragment` element lets the file be removed upon `Clean`. – tm1 Aug 18 '17 at 05:49
-
Without specifying `OutputFile="BuildVersion.cs"`, the task will generate a new unique file name each time it is called. – tm1 Aug 18 '17 at 05:56
-
How can I do this but in .net core 3.1? – afvieira Nov 09 '20 at 17:37
-
how would you add [assembly: InternalsVisibleTo("Namespace.OfYourUnitTest.Project")] if you needed to add testing of internals when using moq to mock up a dependancy? You cant keep making everything public :/ – Doug Thompson - DouggyFresh Jul 05 '21 at 16:01