How to run StyleCop as opt-in feature with msbuild from command line

May 22, 2017

The tool :

So everyone knows wonderful tool from Microsoft, named StyleCop. StyleCop is a tool that runs against C# code (not against IL assemblies – already build code) and based on rules saved either per machine, or per project (we will show us how to save them per project) gives you feedback , if you violated some of these rules. StyleCop started on codeplex (MS take on similar portal like github) and currently moved to GitHub – https://github.com/StyleCop. If you see closely, on GitHub we have two projects :

We will go down the free path and take a look at first option. There are two plugins I will speak about today :

(please note that in StyleCop repo there is a note about recommendation to use Roslyn based StyleCop from https://github.com/DotNetAnalyzers/StyleCopAnalyzers repo)

So, you can add NuGet StyleCop.MSBuild package and now running msbuild from command line will trigger analysis. Which is what we want on CI server, but not for builds from Visual Studio. You can try to run build from VS and see what happens. How to turn off StyleCop.MSBuild for VS builds :

After some search on the interwebz I found out, that there is a property StyleCopEnabled in StyleCop.MSBuild.Targets that is set to true if nothing is specified, which we need to set to false as default. So you need to edit your .csproj (or any other .proj file) and insert

<StyleCopEnabled>false</StyleCopEnabled>

in some PropertyGroup.

This will enable you to do following thing :

  • run msbuild to trigger just plain old build
  • run msbuild /p:StyleCopEnabled=true to pass parameter to msbuild that will do the analysis after the build.

If you guess that the first will be “used” when building from VS and second to get analysis on your CI server, you are right 🙂

And if you questioned yourself, “why not to pass /p:StyleCopEnabled=false” from VS build, then AFAIK from VS also in 2017 we cant just pass parameters to msbuild. Shame, I know.

Hope this helps.


Profile picture

Written by Dušan Roštár - the "mr edge case" guy
my twitter : rostacik, my linkedin : rostar, drop me an email : here