需要Visual Studio宏才能将横幅广告添加到所有C#文件 [英] Need Visual Studio macro to add banner to all C# files

查看:85
本文介绍了需要Visual Studio宏才能将横幅广告添加到所有C#文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以发布一个Visual Studio宏,该宏遍历项目中的所有C#源文件并添加文件标题吗?如果它适用于任何类型的源文件(.cs,.xaml等),都可享有额外的信誉.

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 (.cs, .xaml, etc).

推荐答案

在这里,我为.cs和.vb提供了一个示例,但不难让您根据其他文件类型的需要对其进行调整: 经过编辑可将标题递归添加到子文件夹

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

这篇关于需要Visual Studio宏才能将横幅广告添加到所有C#文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆