Automating Text Search and Replace

Visual Studio .NET gives you the ability to search and replace text in documents open in the IDE and in files on the system. The primary way to accomplish this is using the FindReplace and Execute methods of the Find object. The TextSelection and EditPoint objects also offer the FindPattern method. For more information about that, see the TextSelection.FindPattern() function in Controlling the Code Editor.

Text Search and Replace Example

The following VSA example demonstrates how to reference and use the various members of the Find automation model. This example creates a text document with some text, then searches for and replaces text using different methods. To run different sections of this example, uncomment the appropriate code.

Sub FindReplaceExample()
   Dim FindWin As Find
   Dim Doc As Document
   Dim TD As TextDocument
   Dim TS As TextSelection
   Dim iCtr As Integer

   'Create a new text file.
   DTE.ItemOperations.NewFile("General\Text File")

   'Set up references for the text document, Find object, and
   'TextSelection object.
   Doc = ActiveDocument
   TD = Doc.Object("TextDocument")
   FindWin = DTE.Find
   TS = TD.Selection

   'Insert ten lines of text to work with.
   For iCtr = 1 To 10
      TD.Selection.Text = "This is a test" & Chr(13)
   Next iCtr
   TD.Selection.Text = "This is a different word"

   'Uses Execute to find the word "different" in the document.
   'FindWin.FindWhat = "different"
   'FindWin.MatchCase = True
   'FindWin.Execute()

   'Uses Execute to replace all occurrences of the word "Test" with the 
   'word "replacement."
   'FindWin.FindWhat = "test"
   'FindWin.ReplaceWith = "replacement"
   'FindWin.Action = vsFindAction.vsFindActionReplaceAll
   'FindWin.Execute()

   'Uses FindReplace to find all occurences of the word "test" in the 
   'document.
   MsgBox("Now changing all occurrences of 'test' to 'replacement'.")
   FindWin.FindReplace(vsFindAction.vsFindActionReplaceAll, "test", vsFindOptions.vsFindOptionsMatchCase, "replacement", vsFindTarget.vsFindTargetCurrentDocument, , , vsFindResultsLocation.vsFindResultsNone)
End Sub

See Also

Controlling the Code Editor | Creating and Controlling Environment Windows | Creating Add-Ins and Wizards | Creating an Add-In | Creating a Wizard | Automation and Extensibility Reference | Automation Object Model Chart