StyleCop and the MSBuild Extension Pack

I use StyleCop to check my C# code, running it both manually on particular projects or files from within Visual Studio as well as automatically for all code files as part of the build. The MSBuild Extension Pack provides a Task to run StyleCop from MSBuild. The build file imports the MSBuild Extension Pack tasks and then uses the StyleCop task:

<Project DefaultTargets="RunStyleCop" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
   <Import Project="$(ProgramFiles)MSBuildExtensionPack4.0MSBuild.ExtensionPack.tasks"/>

      <!-- Run StyleCop -->
      <Target Name="RunStyleCop">
         <MSBuild.ExtensionPack.CodeQuality.StyleCop
            remainder not shown ...

However as initially set up this does not work, returning the error: MSB4062: The "MSBuild.ExtensionPack.CodeQuality.StyleCop" task could not be loaded from the assembly C:Program Files (x86)StyleCop 4.7MSBuild.ExtensionPack.StyleCop.dll. Could not load file or assembly 'file:///C:Program Files (x86)StyleCop 4.7MSBuild.ExtensionPack.StyleCop.dll' or one of its dependencies. The system cannot find the file specified. Confirm that the declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

The imported tasks file MSBuild.ExtensionPack.tasks contains an entry for StyleCop <UsingTask AssemblyFile="$(MSBuildProgramFiles32)StyleCop 4.7MSBuild.ExtensionPack.StyleCop.dll" TaskName="MSBuild.ExtensionPack.CodeQuality.StyleCop"/> but the MSBuild.ExtensionPack.StyleCop.dll file is not located in the StyleCop 4.7 folder but is in fact in the same folder as the tasks file, MSBuildExtensionPack4.0.

The obvious move is to change the StyleCop entry in MSBuild.ExtensionPack.tasks to point to the right location i.e. <UsingTask AssemblyFile="$(ExtensionTasksPath)MSBuild.ExtensionPack.StyleCop.dll" TaskName="MSBuild.ExtensionPack.CodeQuality.StyleCop"/>. But this will not work and will return the error “Failed to add file” even though the file named is in fact present.

After a little searching and experimentation it seems that the StyleCop.* DLLs need to be in the same directory as the MSBuild.ExtensionPack.StyleCop.dll for the StyleCop task to work.

The easiest way to get the task working is not to modify the MSBuild.ExtensionPack.tasks StyleCop entry but instead copy the MSBuild.ExtensionPack.StyleCop.dll from the MSBuild Extension Pack folder to the StyleCop 4.7 folder which contains the required DLLs.

Using: MS Build Extension Pack 4.0.7.0; StyleCop 4.7.44.0