2012-01-10 153 views
0

我试图取代一个ASPX页面一些文本使用了Visual Studio(2010)微距文字控制控制标记文本,但似乎控制标记被修改关于更换。替换使用Visual Studio宏

我有一个ASPX页面下面:

<span>Foo</span> 

哪我想,以取代:

<span><asp:Literal Text="<%$ Resources:Foo %>" runat="server" /></span> 

这是由突出“富”的文字和完成然后运行一个宏来替换文本。但是,执行宏时,Visual Studio并不完全按照输入粘贴文本。

我的宏代码看起来是这样的:

Dim Selection As TextSelection = DTE.ActiveDocument.Selection 
Selection.Text = "<asp:Literal Text=""<%$ Resources:Foo %>"" runat=""Server""/>" 

然而,当宏执行时,它会插入此:

<asp:Literal Text=""<%$ Resources:Foo %>" runat="Server" /> %>" 

注意第一组双引号(虽然其他都是正确的)并在最后添加额外的%>"。这似乎发生如果替换文本包含任何引号。例如,如果我只是尝试用<asp:Literal runat=Server"/>替换选定的文本,它可以正常工作。

有谁知道为什么发生这种情况,我怎么能解决这个?

谢谢。

回答

0

最终找到了解决方案,但它更多的是解决办法的。奇怪的行为似乎是部分由Visual Studio中的'粘贴格式代码'设置引起的,当禁用时,它将修复双引号的问题,但不会在最后添加额外的标记。

要解决这个问题,现在我有一个随机字符串替换的文本,然后重写与新的文本文件。这样做的缺点是Visual Studio会提示提示文件已更改,并询问是否应该重新加载,这需要执行以查看更新,但至少实际文件内容现在是正确的。

的代码看起来像这样(简化这个例子):

Sub ReplaceText() 

    'This is the markup we want to replace our selection with 
    Dim LiteralMarkup As String = "<asp:Literal Text=""<%$ Resources:Foo %>"" runat=""Server""/>" 

    'Generate random GUID to do initial replace 
    Dim RandomGuid As String = Guid.NewGuid().ToString() 

    'Now replace the selection with the generated guid 
    DTE.ActiveDocument.Selection.Text = RandomGuid 

    'Save the file 
    DTE.ActiveDocument.Save() 

    'Now replace the generated guid with the real markup that we want 
    Dim NewText As String = File.ReadAllText(DTE.ActiveDocument.FullName).Replace(RandomGuid, LiteralMarkup) 

    'Rewrite the file (will cause VS to prompt user to reload file) 
    File.WriteAllText(CurrentPath, NewText) 

End Sub 

这不是一个理想的解决方案,但它的伎俩。

的人谁的兴趣,此代码正在被设计成方便移动从ASPX或ASCX文件的文本资源文件的过程中宏使用。完整的代码可在此处获得:https://gist.github.com/1591239