Visual Studio 2010: Replacing text in a project item through automation
I automatically instantiate Visual Studio project items through the object model. In some files I need to do text replacements. What is the best approach to do text replacements on the contents of a project item (an xml file for example) using the object model, so Visual Stuido takes care of required source control action. I prefer not to open the fi开发者_开发问答le into the editor, and do text replacements through the editor object model.
Use TextDocument.ReplacePattern method. You can get TextDocument object from the ProjectItem object like this:
DirectCast(ProjectItem.Document.Object, TextDocument)
The complete code is as follows:
Dim pi As ProjectItem = ...
Dim win As EnvDTE.Window = Nothing
If Not pi.IsOpen Then
win = pi.Open(Constants.vsViewKindPrimary)
'uncomment the following line if you want to show opened document
'win.Visible=True
End If
Dim td As TextDocument = DirectCast(pi.Document.Object, TextDocument)
td.ReplacePattern("abc", "def")
If Not win Is Nothing Then
win.Close(vsSaveChanges.vsSaveChangesYes)
End If
精彩评论