Need Visual Studio macro to add banner to all C# files

后端 未结 3 1546
逝去的感伤
逝去的感伤 2020-12-16 02:37

Can someone post a Visual Studio macro which goes through all C# source files in a project and adds a file banner? Extra credit if it works for any type of source file (.c

3条回答
  •  清歌不尽
    2020-12-16 02:48

    Here you go, I provide an example for .cs and .vb but shouldn't be hard for you to adjust it to your other file type needs: Edited to recursively add header to sub-folders

    Sub IterateFiles()
        Dim solution As Solution = DTE.Solution
        For Each prj As Project In solution.Projects
            IterateProjectFiles(prj.ProjectItems)
        Next
    End Sub
    
    Private Sub IterateProjectFiles(ByVal prjItms As ProjectItems)
        For Each file As ProjectItem In prjItms
            If file.SubProject IsNot Nothing Then
                AddHeaderToItem(file)
                IterateProjectFiles(file.ProjectItems)
            ElseIf file.ProjectItems IsNot Nothing AndAlso file.ProjectItems.Count > 0 Then
                AddHeaderToItem(file)
                IterateProjectFiles(file.ProjectItems)
            Else
                AddHeaderToItem(file)
            End If
        Next
    End Sub
    
    Private Sub AddHeaderToItem(ByVal file As ProjectItem)
        DTE.ExecuteCommand("View.SolutionExplorer")
        If file.Name.EndsWith(".cs") OrElse file.Name.EndsWith(".vb") Then
            file.Open()
            file.Document.Activate()
    
            AddHeader()
    
            file.Document.Save()
            file.Document.Close()
        End If
    End Sub
    
    Private Sub AddHeader()
        Dim cmtHeader As String = "{0} First Line"
        Dim cmtCopyright As String = "{0} Copyright 2008"
        Dim cmtFooter As String = "{0} Footer Line"
    
        Dim cmt As String
    
        Select Case DTE.ActiveDocument.Language
            Case "CSharp"
                cmt = "//"
            Case "Basic"
                cmt = "'"
        End Select
        DTE.UndoContext.Open("Header Comment")
        Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
        ts.StartOfDocument()
        ts.Text = String.Format(cmtHeader, cmt)
        ts.NewLine()
        ts.Text = String.Format(cmtCopyright, cmt)
        ts.NewLine()
        ts.Text = String.Format(cmtFooter, cmt)
        ts.NewLine()
        DTE.UndoContext.Close()
    End Sub
    

提交回复
热议问题