Ignore Specific files for a target framework on C#

Tsuyoshi Ushio
2 min readMay 2, 2020

--

I wrote code for a repo that has two target frameworks. One is netstandard the other is net461 . I wanted to ignore some .cs file when I compile net461 binary.

Compile item doesn’t work

My colleague told me about the solution.

You can use Comple like this:

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.0" />
<Compile Include="*.cs" Exclude="AspNetThreadPrincipalModule.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net471'">
<Reference Include="System.Web" />
<Reference Include="System.Configuration" />
<Compile Include="*.cs" />
</ItemGroup>

Oh! Yes. This is what I wanted! So I implement it, however, net461 keep on emitting error. The element seems ignored. Hmm.

When I compiled the project, I can see this error message less than a second. It is gone very quickly.

Duplicate ‘Compile’ items were included. The .NET SDK includes ‘Compile’ items from your project directory by default.

Solution

I see, Let’s see the official document.

With the move to the csproj format in the latest SDK versions, we’ve moved the default includes and excludes for compile items and embedded resources to the SDK properties files. This means that you no longer need to specify these items in your project file.

I see the point. We need to change the default settings if we want to change it. This config is the one.

<PropertyGroup>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>

I configure like this. I want to ignore the files under the Correlation directory.

<ItemGroup>
<!--Don't include Correlation classes in Function V1.-->
<Compile Include="**/*.cs" Exclude="Correlation/*.cs" Condition="'$(TargetFramework)' != 'netstandard2.0'" />
</ItemGroup>

However, I still have errors. Hmm…. I searched the project, however, can’t find System.Reflection.AssemblyCompanyAttribute .

Duplicate ‘System.Reflection.AssemblyCompanyAttribute’ attribute

I happened to realized that that option try to build cs files under the obj dir.

the cs file found

Now things are easy.

<ItemGroup>
<!--Don't include Correlation classes in Function V1.-->
<Compile Include="**/*.cs" Exclude="Correlation/*.cs;**/obj/**/*.cs" Condition="'$(TargetFramework)' != 'netstandard2.0'" />
</ItemGroup>

It works!

Happy coding!

Resource

--

--