Include file in solution explorer without it being a build dependency

1.1k views Asked by At

How can I include a file in the list of files in solution explorer without including it as a dependency for compilation?

I have a .targets file that generates .cs files, similar to the examples in this answer.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <CoreCompileDependsOn>$(CoreCompileDependsOn);GenerateCode</CoreCompileDependsOn>
  </PropertyGroup>

  <ItemGroup>
    <Sources Include="..\sources\*.txt" />
  </ItemGroup>

  <Target Name="GenerateCode" Inputs="@(Sources)" Outputs="@(Sources->'generated\%(Filename).cs')">
    <!-- run executable that generates files -->
    <ItemGroup>
      <Compile Include="generated\*.cs" />
    </ItemGroup>   
  </Target>
</Project>

This builds correctly and consecutive builds don't rebuild the project unnecessarily. The resulting .cs files are not visible in the solution explorer. The generated code also isn't found by intellisense.

If I add the files with ItemGroups in the .csproj, the generated files are visible in the solution explorer, but subsequent builds result in rebuilding the project unnecessarily. The genereated code still isn't found by intellisense.

  <ItemGroup>
    <Sources Include="..\sources\*.txt">
      <Link>sources\%(Filename)%(Extension)</Link>
    </Sources>
    <!-- using None instead of Compile on the next line makes no difference -->
    <Compile Include="@(Sources->'generated\%(Filename).cs')">
      <Generator>MSBuild:Compile</Generator>
      <Link></Link>
    </Compile>
  </ItemGroup>

How can I tell msbuild that the .cs files included in the project are inconsequential to the build and therefore shouldn't trigger rebuilding the entire project?

1

There are 1 answers

0
Cirdec On BEST ANSWER

Move the code generation to BeforeCompile instead of CoreCompileDependsOn. this will keep the generation of the files from tirggering the subsequent builds.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="BeforeCompile" DependsOnTargets="GenerateCode">        
  </Target>

  <Target Name="GenerateCode" Inputs="@(Sources)" Outputs="@(Sources->'generated\%(Filename).cs')">
    <!-- run executable that generates files -->
  </Target>
</Project>

If you include all of the generated files in the .csproj, the visual studio intellisense will work.

  <ItemGroup>
    <Sources Include="..\sources\*.txt">
      <Link>sources\%(Filename)%(Extension)</Link>
      <LastGenOutput>generated\%(Filename).cs</LastGenOutput>
    </Sources >
    <Compile Include="@(Sources->'generated\%(Filename).cs')">
      <Link></Link>
    </Compile>
  </ItemGroup>