MSBuildTreatWarningsAsErrors does not work on Visual Studio 2022

Viewed 52

I want the build to fail when there's a warning. I have the following at .csproj

<PropertyGroup>
     <MSBuildTreatWarningsAsErrors>true</MSBuildTreatWarningsAsErrors>
 </PropertyGroup>

When I try to build from Build menu or Ctrl + B, the build output shows an error but it succeeds:

enter image description here

If I build from command line with dotnet build, it fails as expected.

Environment: Visual Studio 2022 Professional, .NET 6.0

1 Answers

There is an important note on the documentation page for this, which I originally thought might be the reason, but then I tried myself.

My .csproj looks like this for each configuration:

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <TreatWarningsAsErrors>True</TreatWarningsAsErrors>
  </PropertyGroup>

This was added to the .csproj file after I enabled the control:

control

The compiler properly highlights this warning as an error now, and includes it in the errors list:

warning as error

error list

When I perform a build, it also marks it as failed and outputs the errors:

Build started...
1>------ Build started: Project: netcoreapi, Configuration: Debug Any CPU ------
Restored C:\path\repos\netcoreapi\netcoreapi\netcoreapi.csproj (in 17 ms).
1>You are using a preview version of .NET. See: https://aka.ms/dotnet-core-preview
1>C:\path\netcoreapi\netcoreapi\Controllers\TestController.cs(14,20,14,31): error CS0219: The variable 'dummyString' is assigned but its value is never used
1>Done building project "netcoreapi.csproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Try changing the .csproj to use <TreatWarningsAsErrors> instead for each configuration.

Related