修复 Visual Studio 中的 "Duplicate 'Compile' items were included." 错误

Fixing the "Duplicate 'Compile' items were included." error in Visual Studio

这是一个非常烦人的 VS 错误,我在 VS 2019 16.8.1

我花了很多时间修复它:

Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'Program.cs' Service.Host Files\dotnet\sdk.0.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.DefaultItems.targets 295

我不明白是什么导致了这个错误。 我注释掉了*.csproj文件中的Include标签,但问题是我有30多个项目,突然之间它们都有相同的重复错误,通过所有这些来修复这样一个神秘的错误似乎是不安全的操作,其中一些项目是很长时间没有被触及的遗留项目。 评论 Include 标签的解决方案中的另一个问题是我有一些包含结构的项目:

  <ItemGroup>
    <Compile Include="Contracts.cs" />
    <Compile Include="IKey.cs">
      <DependentUpon>Contracts.cs</DependentUpon>
    </Compile>
    <Compile Include="ISigner.cs">
      <DependentUpon>Contracts.cs</DependentUpon>
    </Compile>
  </ItemGroup>

评论这会影响项目结构。

我试图注释掉文件中的 CheckForDuplicateItems 标签:

"C:\Program Files\dotnet\sdk.0.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.DefaultItems.targets",

错误消失了。

编辑

我刚刚注意到目标文件路径中包含 .NET 5 版本 (..\sdk.0.101..),我只有一个项目使用 .NET 5,这会导致问题吗?

.NET5 使用新样式的项目,它会自动将许多文件包含到您的项目中。这有助于使项目文件保持较小,并且不会导致每次添加、删除或重命名文件时都检查和更改它们。一次为所有项目修复此问题的最简单方法可能是在项目的根文件夹中添加一个 directory.build.props 以一次为所有项目设置 <EnableDefaultCompileItems>false<EnableDefaultCompileItems>

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

不要编辑sdk 目录中的任何文件,它们是当前和未来所有项目的默认设置。相反,您可以将这些设置添加到您的项目文件或解决方案全局文件的这些目录中,以便在特定文件夹或解决方案中为您的项目更改它们。

参见: