Upon searching for a way to replace occurences in text files, I only found methods that had to read the entire text file into the memory. These methods cannot be used for large files. That's why I have created this method:
I hope you can use and test this method of replacing strings in a text file. Please let me know when there are bugs in the method so that I can further develop it.Code:/* * This method will replace all occurences of 'search' with 'replace' in the file with URI 'filepath' and backup the * original file to the 'backup' URI. * If 'ignoreEndsOfLine' is true, the method will also replace occurences that are split over * multiple lines in the text. In that case, the file will also be rewritten on a single line. */ public static void replaceInTextFile(string filepath, string search, string replace, bool ignoreEndsOfLine, string backup) { if (search == "" || search == null) { throw new ArgumentException("'search' cannot be null or an empty string", "search"); } StreamReader sr = new StreamReader(filepath); StreamWriter sw = new StreamWriter("TEMP" + filepath); char[] buffer = new char[search.Length]; for (int i = 0; i < buffer.Length; i++) { buffer[i] = (char)0; } while (sr.Peek() != -1) { if (new string(buffer) == search) { sw.Write(replace); for (int i = 0; i < buffer.Length; i++) { buffer[i] = (char)0; } } else { if (buffer[0] != (char)0) { sw.Write(buffer[0]); } for (int i = 0; i < buffer.Length; i++) { if (i < buffer.Length - 1) { buffer[i] = buffer[i + 1]; } else { while (((char)sr.Peek() == (char)10 || (char)sr.Peek() == (char)13) && ignoreEndsOfLine) { sr.Read(); } buffer[i] = (char)sr.Read(); } } } } if (new string(buffer) == search) { sw.Write(replace); } else { for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != (char)0) { sw.Write(buffer[i]); } } } sr.Close(); sw.Close(); FileInfo fi = new FileInfo("TEMP" + filepath); fi.Replace(filepath, backup, true); }


Reply With Quote

Bookmarks