Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply dotnet-format on save in Visual Studio?

I just discovered dotnet-format, but as far as I understand it's a command line tool that has to be called manually. How can I apply dotnet-format on saving a file in Visual Studio 2019? (not Visual Studio Code!)

like image 728
stefan.at.wpf Avatar asked Jan 31 '26 06:01

stefan.at.wpf


2 Answers

Although this is not what the question was about, I have dotnet-format setup to run as a pre-commit hook.

#!/bin/sh
dotnet-format
exit 0

For the on-save formatting and other gimmicks, I use CodeMaid. https://marketplace.visualstudio.com/items?itemName=SteveCadwallader.CodeMaid

like image 109
Ε Г И І И О Avatar answered Feb 01 '26 21:02

Ε Г И І И О


I've gathered all the instructions in one place for multiple IDEs, including Visual Studio, to make them easier to find and use

Visual Studio

  1. Install WillFuqua.RunOnSave extension
  2. Create .onsaveconfig file in the root folder in your project
[*.cs]
command = dotnet
arguments = format "{solution_directory}\YourProjectName.sln" --include {filename} --verbosity diagnostic
  1. Replace YourProjectName.sln with your actual solution file name ({solution_directory} and {filename} remain unchanged)
  2. (Optional) Delete --verbosity diagnostic if you don’t need detailed logs (see docs)
  3. (Optional) Add more options for RunOnSave extension, for example "always_run = true" (see docs)
  4. Restart Visual Studio
  5. Change any *.cs file (especially when always_run is disabled) and save it, then wait a few seconds or minutes

The formatting should be applied automatically.


If the instructions above don't work, try the following troubleshooting steps:

  • Run dotnet format in your project. If the command fails, the issue is likely with the tool itself (e.g., not installed, incorrect .editorconfig configuration, or another setup problem)
  • Go to "View" -> "Output" -> "Run On Save" (from the dropdown menu) and look at the output. A correct output should look like this:

How to open Run on Save

Special thanks to waf for this extension!

VS Code

  1. Install emeraldwalk.RunOnSave extension
  2. Create .vscode/settings.json file in the root folder in your project
{
  "emeraldwalk.runonsave": {
    "commands": [
      {
        "match": "\\.cs$",
        "cmd": "dotnet format ./YourProjectName.sln --include ${relativeFile} --verbosity diagnostic"
      }
    ]
  }
}
  1. Replace ./YourProjectName.sln with your actual solution file name (everything else remains unchanged)

Rider

This article offers a solid guide to setting up formatting (see the Dotnet Format section). However, some parts are slightly outdated. The main difference lies in the arguments:

  • Program: dotnet
  • Arguments: format $SolutionPath$ --include $FileName$ --verbosity diagnostic

Everything else remains the same

like image 21
kurnakovv Avatar answered Feb 01 '26 21:02

kurnakovv