Search code examples
c#namespaces

Remove unused namespaces across a whole project or solution at once


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?


Solution

  • 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