9

I set up an editorconfig file for my project and it works perfectly in my IDE and throws the right warnings. Examples: IDE0052 (unused variables) and IDE0055 (wrong formatting).

However, I would like to enforce the warnings from my editorconfig as errors during Build so that it fails. Is there any way to do this? Setting properties "MSBuildTreatWarningsAsErrors" or "TreatWarningsAsErrors" to true in the csproj hasn't done anything.

Thank you!

1 Answers1

12

I think you need two things to make this work.

Firstly, in your .csproj file set the following:

<PropertyGroup>
    <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>

Secondly, in your .editorconfig file use the following format to set the severity level when building

dotnet_diagnostic.IDE0052.severity = error

Without the first part, I was only able to get an error generated on the build but that wouldn't cause the build to fail (oddly enough).

This test was run using VS 2019 v16.8.4

Check out this resource for more information code-analysis-overview

bernieslearnings
  • 1,424
  • 4
  • 17
  • 27
  • 1
    Thank you for your answer! According to the resource, it only works from .NET 5 onwards. – ilovestackoverflow Mar 08 '21 at 07:08
  • What .net version are you using? – bernieslearnings Mar 08 '21 at 23:09
  • 1
    4.8. I already asked the project lead to update, it wil be a matter of time. – ilovestackoverflow Mar 09 '21 at 07:58
  • 1
    I tried dotnet_diagnostic.IDE0003.severity = error but it doesn't seem to work – Andrew Chaa Jun 16 '21 at 11:53
  • 1
    You can use `dotnet_analyzer_diagnostic.severity = default` to get msbuild to imitate the default VS severities, rather than having to set them explicitly. (Not sure why it's needed.) – Kyle McClellan Aug 05 '21 at 14:02
  • 1
    Is there any way to change severity based on the build configuration? In the CA days, violations could raise warnings, and for Release builds we would enable "Treat Warnings as Errors". This would allow team members to develop and debug with style errors, but force them to fix it before making a production build. – nicholas Sep 07 '21 at 03:26