项目中会碰到需要批量替换修改html、txt等文件的内容,以下贴出我的一个工具类
//读取需要替换的文本
String pathTemp = System.Environment.CurrentDirectory + "\\temp.html";
String html = File.ReadAllText(@pathTemp);
//读取目录下所有需要替换的文件
String path = System.Environment.CurrentDirectory + "\\chapter_txt\\";
DirectoryInfo imagesfile = new DirectoryInfo(path);
FileInfo []files=imagesfile.GetFiles("*.txt");
foreach (FileInfo file in files)//遍历需要替换的文件进行替换
{
String content = File.ReadAllText(file.FullName);
String new_html = html.Replace("#CONTENT", content);
String new_path = path+file.Name.Replace("txt", "html");
//重新写入文件
StreamWriter sW = new StreamWriter(@new_path);
sW.Write(new_html);
sW.Close();
}
具体操作过程中有遇到什么问题,可联系我个人微信讨论