【问题标题】:Why Can't I do String.Replace() on a IO.File.ReadAllText() string?为什么我不能对 IO.File.ReadAllText() 字符串执行 String.Replace()?
【发布时间】:2009-07-11 00:18:48
【问题描述】:

我正在使用 System.IO.FIle.ReadAllText() 来获取我为电子邮件内容创建的一些模板文件的内容。然后我想对文件中的某些标记进行替换,以便可以向模板添加动态内容。

这是我的代码,在我看来它应该可以正常工作......

Dim confirmUrl As String = Request.ApplicationPath & "?v=" & reg.AuthKey
Dim text As String = IO.File.ReadAllText( _
   ConfigurationManager.AppSettings("sign_up_confirm_email_text").Replace("~", _
   Request.PhysicalApplicationPath))
Dim html As String = IO.File.ReadAllText( _
   ConfigurationManager.AppSettings("sign_up_confirm_email_html").Replace("~", _
   Request.PhysicalApplicationPath))

text.Replace("%%LINK%%", confirmUrl)
text.Replace("%%NAME%%", person.fname)

html.Replace("%%LINK%%", confirmUrl)
html.Replace("%%NAME%%", person.fname)

由于某种原因,我无法使 %%LINK%% 和 %%NAME%% Replace() 调用正常工作。我检查了它是否与编码相关,所以我将每个文件都设为 UTF-8。并且还使用了 ReadAllText(String, Encoding) 的强制编码重载,仍然没有骰子。有什么想法吗?

【问题讨论】:

    标签: vb.net string .net


    【解决方案1】:

    问题是字符串在 .NET 中是不可变的。所以你的替换代码应该是这样的:

    text = text.Replace("%%LINK%%", confirmUrl);
    text = text.Replace("%%NAME%%", person.fname);
    
    html = html.Replace("%%LINK%%", confirmUrl);
    html = html.Replace("%%NAME%%", person.fname);
    

    【讨论】:

    • 很多人会争辩说,让 Replace() 成为一个非静态函数对 .NET 设计者来说是愚蠢的,所以不要感觉那么糟糕 ;-)
    • 是的,我认为每个 .NET 开发人员(还有Java,如果我没记错的话)在某些时候遇到过这种情况。甚至完全知道字符串的不变性。见鬼,我还是有时会忘记使用返回值。
    猜你喜欢
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多