Joe*_*oey 23 c# file-io fileinfo streamwriter
替换HTML文件内容的一部分时,String.Replace似乎无法正常工作.例如,String.Replace替换</body></html>为blah blah blah </body></html> html> - 注意第二个HTML结束标记未正确关闭,因此在用户在浏览器中呈现页面时显示.
任何人都知道它为什么不按预期工作?
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();
Run Code Online (Sandbox Code Playgroud)
Nat*_*ate 56
我可能会像这样重写你的代码:
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);
Run Code Online (Sandbox Code Playgroud)
我应该注意,这个解决方案适用于合理大小的文件.取决于硬件,任何低于几十MB的东西.它将整个内容加载到内存中.如果你有一个非常大的文件,你可能需要一次流几百KB来防止OutOfMemoryException.这使得事情变得更复杂,因为您还需要检查每个块之间的中断以查看是否拆分了搜索字符串.
Jon*_*eet 14
这里没有错string.Replace.
什么是错的,你覆盖文件,但不截断它......所以如果你改变了你写代码,只是
sw.WriteLine("Start");
Run Code Online (Sandbox Code Playgroud)
你会看到"开始",然后是文件的其余部分.
我建议您使用File.ReadAllText而File.WriteAllText不是(从中获取路径FileInfo).那样:
如果您确实想使用FileInfo方法,请使用FileInfo.Open(FileMode.Create)哪个方法截断文件.