Remove unused namespaces across a whole project or solution at once

C#Namespaces

C# Problem Overview


I know you can do it file by file.

Is there any way to do this in one step for all files in a project?

C# Solutions


Solution 1 - C#

There is no need for any plugins in VS 2017 or 2019. Click the bulb icon near any using statement and click Solution next to Fix all occurrences in part.

Screenshot of solution

Solution 2 - C#

The other answers which refer to the Productivity Power Tools extensions don't go into any detail of how to actually do this, so here are some instructions for Visual Studio 2013, 2015, 2017 and 2019:

First, open the Tools > Extensions and Updates... dialog in Visual Studio, select Online in the left-hand bar and then search the Visual Studio Gallery for "Productivity Power Tools". Install the extension and restart VS.

Alternatively, you can manually download and install the extensions for your version of Visual Studio:

Productivity Power Tools 2013
Productivity Power Tools 2015
Productivity Power Tools 2017/2019

For VS2017 and VS2019, you can also download the Power Commands extension separately from the others in the Power Tools pack:

Power Commands for Visual Studio

Be aware that at the time of writing, the VS2017 version doesn't work with .Net Core projects/solutions.

Once you have the extension installed, just right-click the solution in Solution Explorer, then select Power Commands > Remove and Sort Usings.

This can take a while, particularly on large solutions; it also doesn't keep modified files open (hence no undo), so make sure you commit everything in your VCS of choice before running it, so that you can revert the changes it makes if something goes wrong!

Update: Format All Files

Recently I've been using the Format All Files extension, which allows you to execute Format Document, Remove and Sort Usings and one other custom command of your choice (all optionally, set in the VS preferences).

It seems to work very well, but again, no undo, so make sure you commit everything in your VCS of choice before running it.

Solution 3 - C#

Do you mean using statements? First, note that they generally do no harm other that take space. Tools like ReSharper offer automated tricks to do this, however: there was a link in the VS feed a little while ago; it boils down to:

  • go to Tools -> Macros -> Macros IDE...
  • in the Project Explorer, Add -> Add Module... (put in a name - I've used OrganiseUsings)
  • paste over with the code below
  • File -> Save MyMacros, exit

Now if you right-click on the toolbar and Customize... - you should be able to find MyMacros.OrganiseUsings.RemoveAndSortAll - drag this somewhere handy (maybe the Tools menu; you might also want to change the name after placing it).

You can now use this option to run the Remove and Sort command for an entire solution. A big time-saver.

==== code ====

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics

Public Module OrganiseUsings

    Public Sub RemoveAndSortAll()
        On Error Resume Next
        Dim sol As Solution = DTE.Solution

        For i As Integer = 1 To sol.Projects.Count    
            Dim proj As Project = sol.Projects.Item(i)    
            For j As Integer = 1 To proj.ProjectItems.Count    
                RemoveAndSortSome(proj.ProjectItems.Item(j))    
            Next    
        Next    
    End Sub    
    
    Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem)
        On Error Resume Next
        If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then    
            If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then
                Dim window As Window = projectItem.Open(Constants.vsViewKindCode)

                window.Activate()

                projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort")

                window.Close(vsSaveChanges.vsSaveChangesYes)
            End If    
        End If    

        For i As Integer = 1 To projectItem.ProjectItems.Count    
            RemoveAndSortSome(projectItem.ProjectItems.Item(i))    
        Next
    End Sub   

End Module

Solution 4 - C#

For Visual Studio 2010 you can download the "Remove and Sort Using"extension from the Visual Studio Gallery.

http://visualstudiogallery.msdn.microsoft.com/en-us/cb559aa8-d976-4cc2-9754-5a712f985d16

Works Well for me

Solution 5 - C#

There is a built-in function under the analyze menu that is called as Code Cleanup. If you click Profile 1, it'll do as remove and sortings functionality.

enter image description here

Solution 6 - C#

If you do mean 'using' Power Commands contains this functionality + a boat load more.

http://code.msdn.microsoft.com/PowerCommands

Solution 7 - C#

Productivity Power tools is what you need. https://visualstudiogallery.msdn.microsoft.com/dbcb8670-889e-4a54-a226-a48a15e4cace

Once you have that installed, you can find the “Remove and Sort Usings on Save” from the “Tools –> Options –> Productivity Power Tools –> PowerCommands –> Generals”. After you check that option, restart VS. Now save and you see the magic.

For VS 2015, take a look at this

Solution 8 - C#

for a more recent version, including 2017, try the "Format All Files" extension. it has been working really well for me.

enter image description here

Solution 9 - C#

Here's a small improvement on the script above for VB.NET. Make sure you have the Productivity Power Tools installed.

    Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem)
    On Error Resume Next
    If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then
        If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then
            Dim window As Window = projectItem.Open(Constants.vsViewKindCode)

            window.Activate()

            projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort")

            window.Close(vsSaveChanges.vsSaveChangesYes)

        ElseIf projectItem.Name.LastIndexOf(".vb") = projectItem.Name.Length - 3 Then
            Dim window As Window = projectItem.Open(Constants.vsViewKindCode)

            window.Activate()

            projectItem.Document.DTE.ExecuteCommand("EditorContextMenus.CodeWindow.OrganizeImports.RemoveandSortImports")

            window.Close(vsSaveChanges.vsSaveChangesYes)
        End If
    End I

Solution 10 - C#

I am using Visual Studio 2015 and found a tool named BatchFormat: https://marketplace.visualstudio.com/items?itemName=vs-publisher-147549.BatchFormat

This did the job perfectly.

Install the tool, then right click on your solution in the solution explorer, then at the top of the menu you see batch format:

enter image description here

Whatever you select is applied to every file in your solution, as you can see in the screenshot, there are other options, you can also format every document.

Solution 11 - C#

visual studio 2017 having inbuild feature to remove unnecessary name space from whole project.

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#sotnView Answer on Stackoverflow
Solution 2 - C#Mark BellView Answer on Stackoverflow
Solution 3 - C#Marc GravellView Answer on Stackoverflow
Solution 4 - C#vmachacekView Answer on Stackoverflow
Solution 5 - C#Murat Can OĞUZHANView Answer on Stackoverflow
Solution 6 - C#MeshView Answer on Stackoverflow
Solution 7 - C#VivekDevView Answer on Stackoverflow
Solution 8 - C#Dave ThiebenView Answer on Stackoverflow
Solution 9 - C#mghaouiView Answer on Stackoverflow
Solution 10 - C#Tim PickinView Answer on Stackoverflow
Solution 11 - C#Sangeet ShahView Answer on Stackoverflow