Skip to content

Instantly share code, notes, and snippets.

@dadhi
Forked from KirillOsenkov/AddGeneratedFile.csproj
Created October 9, 2019 18:26
Show Gist options
  • Select an option

  • Save dadhi/549debff1411b416f7ab0cf7d41383d4 to your computer and use it in GitHub Desktop.

Select an option

Save dadhi/549debff1411b416f7ab0cf7d41383d4 to your computer and use it in GitHub Desktop.
Sample of generating a .cs file during build and adding it to the compilation
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net472</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<GeneratedText><![CDATA[
using System%3B
public class Hello$(TargetFramework)
{
public void Print()
{
Console.WriteLine("Hello $(TargetFramework)!")%3B
}
}
]]></GeneratedText>
</PropertyGroup>
<Target Name="AddGeneratedFile" BeforeTargets="BeforeCompile;CoreCompile" Inputs="$(MSBuildAllProjects)" Outputs="$(IntermediateOutputPath)GeneratedFile.cs">
<PropertyGroup>
<GeneratedFilePath>$(IntermediateOutputPath)GeneratedFile.cs</GeneratedFilePath>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(GeneratedFilePath)" />
<FileWrites Include="$(GeneratedFilePath)" />
</ItemGroup>
<WriteLinesToFile Lines="$(GeneratedText)" File="$(GeneratedFilePath)" WriteOnlyWhenDifferent="true" Overwrite="true" />
</Target>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment