C#文件内更换串 [英] c# replace string within file

查看:182
本文介绍了C#文件内更换串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与string.replace似乎并没有取代HTML文件的内容的一部分时,才能正常工作。例如,与string.replace替换< /身体GT;< / HTML> 等等等等< /身体GT;< / HTML> HTML> - 请注意第二个HTML结束标记不proberly关闭,因此显示了当页面在用户浏览器中呈现。



任何人都知道为什么它不按预期工作?

  StreamReader的SR = fi.OpenText; 
字符串fileContents = sr.ReadToEnd();
sr.close();
fileContents = fileContents.Replace(&所述;主体>中,&所述;身体的onload ='jsFx();/>中);
fileContents = fileContents.Replace(< /身体GT;,等等等等< /身体GT;);

StreamWrtier SW =新的StreamWriter(fi.OpenWrite());
sw.WriteLine(内容);
sw.close();


解决方案

我可能会改写你对这样的代码位:

  VAR fileContents = System.IO.File.ReadAllText(@C:\File.html); 

fileContents = fileContents.Replace(&所述;主体>中,&所述;身体的onload ='jsFx();/>中);
fileContents = fileContents.Replace(< /身体GT;,等等等等< /身体GT;);

System.IO.File.WriteAllText(@C:\File.html,fileContents);



我要指出,这个解决方案是罚款合理大小的文件。根据硬件,下一个几十MB的任何事情。它装载的全部内容存入存储器。如果你有一个非常大的文件,您可能需要在时间,以防止一个OutOfMemoryException通过几百KB流吧。这使事情变得有点复杂,因为你还需要检查每块之间的休息,如果拆分搜索字符串。


String.Replace doesn't seem to work properly when replacing a portion of an HTML file's content. For example, String.Replace replaces </body></html> with blah blah blah </body></html> html> - notice the second HTML closing tag is not proberly closed and therefore shows up when the page is rendered in the browser by the user.

Anyone know why it's not working as intended?

StreamReader sr = fi.OpenText;
String fileContents = sr.ReadToEnd();
sr.close();
fileContents = fileContents.Replace("<body>", "<body onload='jsFx();' />");
fileContents = fileContents.Replace("</body>","blah blah blah </body>");

StreamWrtier sw = new StreamWriter(fi.OpenWrite());
sw.WriteLine(contents);
sw.close();

解决方案

I might rewrite your bit of code like this:

var fileContents = System.IO.File.ReadAllText(@"C:\File.html");

fileContents = fileContents.Replace("<body>", "<body onload='jsFx();' />"); 
fileContents = fileContents.Replace("</body>","blah blah blah </body>"); 

System.IO.File.WriteAllText(@"C:\File.html", fileContents);

I should note that this solution is fine for files of reasonable size. Depending on hardware, any thing under a few tens of MB. It loads the entire contents into memory. If you have a really large file you may need to stream it through a few hundred KB at a time to prevent an OutOfMemoryException. That makes things a bit more complicated, since you'd need to also check the break between each chunk to see if split your search string.

这篇关于C#文件内更换串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆