MSBuild or NAnt script that generates C# files, adds them to a project and compiles the project

StackOverflow https://stackoverflow.com/questions/21591363

  •  07-10-2022
  •  | 
  •  

Question

I've just written a code generator app for FluentMigrator API that emits an unknown number of C# class files. I wish to compile the code generator, run it to emit the C# classes then add the new C# files to an existing C# project and then compile final solution.

What's the best approach for adding the code generated C# files to a project?

Was it helpful?

Solution

Given what we know from your post, there could be a couple approaches.

You have an API that will generate some class files and want to integrate this into your build process so you would make an API call to generate new class files, then incorporate those class files into your build.

If your executable emits output files into it's current working directory, you could use an Exec task to run your command in the $(IntermeidateOutputPath) so as to not clutter up your project's source tree:

<Exec Command="MyExe.exe " WorkingDirectory="$(IntermediateOutputPath)\AutoGenClasses\" />

Following this command, you could append those output classes into the default compile group:

<ItemGroup>
  <Compile Include="$(IntermediateOutputPath)\AutoGenClasses\**\*.cs" />
</ItemGroup>

Now you'd probably want to control when this occurs, so you'd embed this code into a separate <Target /> and schedule it to occur before the build occurs.

<Target Name="AutoGenClasses" BeforeTargets="Compile">
  <Message Text="Starting the AutoGenClasses task..." Importance="high" />
  <Exec Command="MyExe.exe " WorkingDirectory="$(IntermediateOutputPath)\AutoGenClasses\" />
  <ItemGroup>
    <Compile Include="$(IntermediateOutputPath)\AutoGenClasses\**\*.cs" />
  </ItemGroup>
  <Message Text="... completed the AutoGenClasses." Importance="high" />
</Target>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top