为什么我不能在IO.File.ReadAllText()字符串上执行String.Replace()?

sho*_*ger 4 .net vb.net string

我正在使用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)
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*kle 13

问题是字符串在.NET中是不可变的.因此,您的替换代码应如下所示:

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

html = html.Replace("%%LINK%%", confirmUrl);
html = html.Replace("%%NAME%%", person.fname);
Run Code Online (Sandbox Code Playgroud)

  • 许多人认为让Replace()成为非静态函数对于.NET设计师来说是愚蠢的,所以不要感觉那么糟糕;-) (2认同)
  • 是的,我认为*每个*.NET开发人员(以及Java,如果我没记错的话)都会遇到这种情况.甚至完全了解字符串的不变性.天啊,我*有时候会忘记使用返回值. (2认同)