Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Macro to Format all Files in a Solution

I've recently settled on a new format style for my code and want to replace the existing code. The only problem is there's 100's if not 1000's of files in my solution and i don't fancy formatting each one individually.

I was wondering how to create a macro to open every file in the solution that has the .cs file extension and simply select all the text and then cut and paste it (which would format it accordingly). It would also be great if it could sort and removing the using statements aswell but this is not that important as i'd imagine this would be a little harder.

I'd appreciate your help. Thanks

like image 243
nfplee Avatar asked Dec 17 '22 20:12

nfplee


1 Answers

Problem solved! The following macro did the trick incase anyone is interested:

   Public Module FormatAll
        Public Sub FormatAll()
            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
                    FormatSome(proj.ProjectItems.Item(j))
                Next
            Next
        End Sub

        Private Sub FormatSome(ByVal projectItem As ProjectItem)
            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.FormatDocument")
                    projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort")
                    window.Close(vsSaveChanges.vsSaveChangesYes)
                End If
            End If

            For i As Integer = 1 To projectItem.ProjectItems.Count
                FormatSome(projectItem.ProjectItems.Item(i))
            Next
        End Sub
    End Module
like image 106
nfplee Avatar answered Jan 16 '23 03:01

nfplee