天天看點

c# .net批量修改檔案内容

項目中會碰到需要批量替換修改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();
            }
           

具體操作過程中有遇到什麼問題,可聯系我個人微信讨論

c# .net批量修改檔案内容

繼續閱讀