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!)
-
See Format document on Save extensionAlexander Petrov– Alexander Petrov2021-04-04 12:57:24 +00:00Commented Apr 4, 2021 at 12:57
-
@AlexanderPetrov ah thanks, got it that dotnet-format is simply the command line tool for the built-in Visual Studio formatting. Thanks!me.at.coding– me.at.coding2021-04-04 13:18:12 +00:00Commented Apr 4, 2021 at 13:18
4 Answers
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
- Install WillFuqua.RunOnSave extension
- Create
.onsaveconfigfile in the root folder in your project
[*.cs]
command = dotnet
arguments = format "{solution_directory}\YourProjectName.sln" --include {filename} --verbosity diagnostic
- Replace
YourProjectName.slnwith your actual solution file name ({solution_directory}and{filename}remain unchanged) - (Optional) Delete
--verbosity diagnosticif you don’t need detailed logs (see docs) - (Optional) Add more options for RunOnSave extension, for example "always_run = true" (see docs)
- Restart Visual Studio
- Change any
*.csfile (especially whenalways_runis 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 formatin your project. If the command fails, the issue is likely with the tool itself (e.g., not installed, incorrect.editorconfigconfiguration, 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:
Special thanks to waf for this extension!
VS Code
- Install emeraldwalk.RunOnSave extension
- Create
.vscode/settings.jsonfile in the root folder in your project
{
"emeraldwalk.runonsave": {
"commands": [
{
"match": "\\.cs$",
"cmd": "dotnet format ./YourProjectName.sln --include ${relativeFile} --verbosity diagnostic"
}
]
}
}
- Replace
./YourProjectName.slnwith 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
Comments
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
