c# replace string within file -


string.replace doesn't seem work when replacing portion of html file's content. example, string.replace replaces </body></html> blah blah blah </body></html> html> - notice second html closing tag not closed , therefore shows when page rendered in browser user.

anyone know why it's not working 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>");  streamwriter sw = new streamwriter(fi.openwrite()); sw.writeline(contents); sw.close(); 

i might rewrite bit of code 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 solution fine files of reasonable size. depending on hardware, thing under few tens of mb. loads entire contents memory. if have large file may need stream through few hundred kb @ time prevent outofmemoryexception. makes things bit more complicated, since you'd need check break between each chunk see if split search string.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -