8

Visual Studio 2008 got two great features for c#, which is called "sort using directives" and "remove unused using directives".

I'd like to call the "sort using directives" every time I format the code using ctrl+k,ctrl+d.

Or, even better, I would like to be able to reformat all c#-source files in a project, and call "sort using directives" for all source files.

How can I do this? Opening every cs-file by hand and typing these functions before every checkin is tedious!

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Sam
  • 28,421
  • 49
  • 167
  • 247

4 Answers4

13

You can do it all for a solution or project using "PowerCommands for Visual Studio 2008". After installation, you just need to right-click on a project or solution and "Remove and Sort Usings" is in the context menu.

EDIT: As noted in comments, there are also PowerCommands for Visual Studio 2010.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yeah, cool. It even can reformat and sort using on file save. Just what I was looking for, thanks! – Sam Jan 16 '09 at 14:18
  • After using the PowerCommands for some days, I find them lacking in one detail: There is no way to just sort usings on save. Sort & remove unused has its problems: Errors on auto-save due to build ("build in progress, can't remove unused"), errors when code does not compile. Sort only would be nice – Sam Jan 22 '09 at 10:24
  • By the way, there are [PowerCommands for Visual Studio 2010](http://visualstudiogallery.msdn.microsoft.com/e5f41ad9-4edc-4912-bca3-91147db95b99) now – Evgeny A. Jan 10 '12 at 04:14
  • Is there a way to sort usings without removing them? – Stefan Sep 12 '19 at 08:55
2

Another option is CodeMaid, a free and open source Visual Studio extension. It allows you to sort usings, remove usings, format document, remove/insert blank lines, remove whitespace, and quite a few more cleanups. It can run on save, solution wide, etc. Follow the link to the visual studio gallery to see more details.

It also lets you conditionally enable/disable individual portions, so with it you can disable remove unused usings and do sort only if you want as you mentioned in the comments.

Disclaimer: I wrote it ;)

Steve Cadwallader
  • 2,656
  • 4
  • 28
  • 37
1

ReSharper can do this for you (among other reformatting options) and it allows you to do an entire solution in one go.

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
1

I recommend you record a macro of you invoking the feature manually. Then you can just save the macro and put a button for it on the toolbar. This way you'll also have a foot in the door to get started really customizing your IDE.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794