7

This question already has an answer here: How do you format code in Visual Studio Code?

All the answers provided in this question are not working with C# code.

I just copied my controller file and opened it in Visual Studio Code. I tried to format code with Shift + Alt + F (both right and left shifts in windows)

But it didn't work.

Is there a solution for this?

The same shortcut is working for HTML and JavaScript files.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
J Santosh
  • 3,808
  • 2
  • 22
  • 43

2 Answers2

4

For C# you need to

  • Open a folder (not a file) that contains at least one .sln file
  • In the bottom bar you will see a blinking flame. Wait until it stops blinking.
  • Click on the flame. You are going to be asked to select a file.
  • In case you selected a .sln file click again on the flame and select a .csproj file.
  • You can now format all .cs files which are part of the selected project using Shift + Alt + F.
Wosi
  • 41,986
  • 17
  • 75
  • 82
  • 1
    I see `Assembly-*.csproj` files in the sidebar, but nothing is available besides my project `.sln` when I click the flame. Any ideas? – jlmakes Jun 07 '16 at 15:03
  • Just so I don't repeat this question for no good reason: Auto formatting doesn't work on c#-code that doesn't belong to a .csproj file that belongs to a .sln file? Come from Java and thought I could just create a compilable helloworld.cs-file in a folder, compile and run it. I completely stopped working when I realized the vscode autoindentation wasn't working, woudn't have imagined that it was because it didn't belong to a project/solution structure. – MrJalapeno Jul 22 '17 at 17:24
  • Re "Shift + Alt + F": [Only in Windows](https://stackoverflow.com/questions/29973357/how-do-you-format-code-in-visual-studio-code-vscode/29973358#29973358)? – Peter Mortensen Jun 13 '20 at 01:40
1

In my case the problem was related with the code formatting extension.

I was using C# for "Visual Studio Code (powered by OmniSharp)" (ms-vscode.csharp) extension for formatting. However, after a while the "format document" context menu has gone missing. And the key combination for formatting "Shift+Alt+F" stopped working.

After some research I have found that there is a new extension called "C# FixFormat" (Leopotam.csharpfixformat) for formatting C# documents which says in their description: "there is bug in omnisharp and they are fixing the issue temporarily".

After installing "C# FixFormat" extension I can now format documents again.

Oncel Umut TURER
  • 569
  • 10
  • 16
  • I will also add that "Visual Studio Code Format" extension conflicted with "C# FixFormat", and once "Visual Studio Code Format" was disabled, it worked for me. – Max Izrin Mar 22 '18 at 14:22