Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Source Generator should refresh/delete emited files

I created a Source Generator to extend (partial) classes which fulfill certain criteria. To check and view the generated code I enabled the emission of these files by adding the following to my project:

    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>

This works as long as I don't do refactoring - like renaming a class. Because for every class a file is generated but not removed when I rename the "source" class.

So I added the following code to clean all generated files (on clean and rebuild)

    <Target Name="CleanSourceGeneratedFiles" AfterTargets="Clean">
        <RemoveDir Directories="Generated" />
    </Target>

However then every second rebuild fails with: Error CS2001 Source file 'xyz.generated.cs' could not be found.

So I'm looking for another way to keep my generated sources up to date, where the project not only compiles every second try.

like image 922
Fritz Avatar asked Jul 31 '26 00:07

Fritz


1 Answers

Try this. It works for me.

  <PropertyGroup>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
    <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
  </PropertyGroup>

  <Target Name="CleanSourceGeneratedFiles" BeforeTargets="BeforeBuild" DependsOnTargets="$(BeforeBuildDependsOn)">
    <RemoveDir Directories="Generated" />
  </Target>

  <ItemGroup>
    <Compile Remove="Generated\**" />
    <Content Include="Generated\**" />
  </ItemGroup>
like image 91
huoshan12345 Avatar answered Aug 03 '26 09:08

huoshan12345



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!