Autoformat C# source code from the command line

Why?

The GoLang blog says it best. Having an automated, canonical, code-formatting tool as part of the build makes your code: "easier to write... easier to read... easier to maintain... [and] uncontroverial."

How?

  1. Install MSBuild Tools 2015.
  2. Download CodeFormatter 1.0.0-alpha6.
  3. Add CodeFormatter.csproj to the root directory of your projects:

CodeFormatter.csproj

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
  <Compile Include="**\*.cs" />
</ItemGroup>
<Target Name="Compile">
  <Csc Sources="@(Compile)"/>
</Target>

Then run this from the Command Line (it helps if you've added the extracted ZIP file to your PATH).

> codeformatter.exe CodeFormatter.csproj /nocopyright

The result: all your projects' C# files now adhere to the majority of the .NET Foundation coding guidelines.

Remarks

  • Installing MSBuild Tools 2015 means that we do not need Visual Studio.
  • Adding CodeFormatter.csproj to the root directory recursively includes all C# files, which means the above works with project.json and *.xproj based setups.