
Today I thought I would create a simple macro to add a copyright message to the top of a C# source file, then remove and sort the usings.
The macro takes a quite simple approach: just create a file called ‘copyright.txt’ and place it at the root (or solution) level of your project. Then when you are editing C# code, run the macro and it will remove and sort ‘using’ statements, and insert your copyright text at the top of your source code.
The result is as follows:
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.IO
Imports System.Diagnostics
Public Module BtlModule
Public Function GetFileContents(ByVal FullPath As String, _
Optional ByRef ErrInfo As String = "") As String
Dim strContents As String
Dim objReader As StreamReader
Try
objReader = New StreamReader(FullPath)
strContents = objReader.ReadToEnd()
objReader.Close()
Return strContents
Catch Ex As Exception
ErrInfo = Ex.Message
End Try
End Function
Sub InsertCopyright()
Dim solutionDir As String = System.IO.Path.GetDirectoryName(DTE.Solution.FullName())
Dim copyright As String = GetFileContents(solutionDir + "\\copyright.txt")
DTE.ActiveDocument.Selection.StartOfDocument()
DTE.ActiveDocument.Selection.LineUp()
DTE.ActiveDocument.Selection.Insert(copyright)
DTE.ActiveDocument.Selection.NewLine()
DTE.ExecuteCommand("Edit.RemoveAndSort")
End Sub
End Module
The only requirement is that you have a ‘copyright.txt’ file at the same level as your .sln. An improvement would be to check that the first line doesn’t already start with a comment, and include the word ‘copyright’.
Lastly, wire up the macro command to your toolbar as follows at http://msdn.microsoft.com/en-us/library/3dy74ad1.aspx
Assigning a Macro to a Toolbar Button
1. Choose Customize from the Tools menu.
2. Choose the Commands tab.
3. Click the Toolbar radio button and select the target toolbar from the drop down list.
4. Click the Add Command… button.
5. Select Macros in the Categories list.
6. Select the desired macro from the Commands list, and then click OK.
7. Click Modify Selection and choose the appropriate commands to modify the appearance of the button, such as renaming it, assigning an image to it, and so on.








