Search code examples
c#xmlmsbuild

The attribute "Include" in element <PackageReference> is unrecognized


I created a Directory.Build.props file by right clicking the Solution on Solution Explorer, creating an XML file, and named it so. I then input this XML and tried building but was met with errors:

<Project>
    <PropertyGroup>
        <Version>1.2.3</Version>
        <Authors>John Doe</Authors>
        <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0">
            <PrivateAssets>all</PrivateAssets>
            <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
        </PackageReference>
    </PropertyGroup>
</Project>

The errors say: The attribute "Include" in element <PackageReference> is unrecognized. and

Project "C:\redacted\Directory.Build.props" was not imported by "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Microsoft.Common.props" at (33,3), due to the file being invalid. ProjectName C:\Users\me\source\redacted\ProjectName\Directory.Build.props   33  

I am so confused here. The other articles said to locate the MSBuild and I know that its on my machine. The build was working just fine prior to me adding the XML too. Any guidance would be very appreciated! I am currently on Visual Studio 2022 by the way.


Solution

  • The PackageReference element needs to be in an ItemGroup - you've got it in a PropertyGroup. It should look like this:

    <Project>
        <PropertyGroup>
            <Version>1.2.3</Version>
            <Authors>John Doe</Authors>
        </PropertyGroup>
    
        <ItemGroup>
            <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0">
                <PrivateAssets>all</PrivateAssets>
                <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
            </PackageReference>
        </ItemGroup>
    </Project>