c# - Replacing a certain word in a text file -
i know has been asked few times, have seen lot of regex etc., , i'm sure there way stream reader/writer. below code. i'm trying replace "tea" word "cabbage". can help? believe have wrong syntax.
namespace week_9_exer_4 { class textimportedit { public void editorialcontrol() { string filename; string linereadfromfile; console.writeline(""); // ask name of file read console.write("which file wish read? "); filename = console.readline(); console.writeline(""); // open file reading streamreader filereader = new streamreader("c:\\users\\greg\\desktop\\programming files\\story.txt"); // read lines file , display them // until null returned (indicating end of file) linereadfromfile = filereader.readline(); console.writeline("please enter word wish edit out: "); string editword = console.readline(); while (linereadfromfile != null) { console.writeline(linereadfromfile); linereadfromfile = filereader.readline(); } string text = file.readalltext("c:\\users\\greg\\desktop\\programming files\\story.txt"); filereader.close(); streamwriter filewriter = new streamwriter("c:\\users\\greg\\desktop\\programming files\\story.txt", false); string newtext = text.replace("tea", "cabbage"); filewriter.writeline(newtext); filewriter.close(); } } }
if don't care memory usage:
string filename = @"c:\users\greg\desktop\programming files\story.txt"; file.writealltext(filename, file.readalltext(filename).replace("tea", "cabbage"));
if have multi-line file doesn't randomly split words @ end of line, modify 1 line @ time in more memory-friendly way:
// open stream source file using (var sourcefile = file.opentext(filename)) { // create temporary file path can write modify lines string tempfile = path.combine(path.getdirectoryname(filename), "story-temp.txt"); // open stream temporary file using (var tempfilestream = new streamwriter(tempfile)) { string line; // read lines while file has them while ((line = sourcefile.readline()) != null) { // word replacement line = line.replace("tea", "cabbage"); // write modified line new file tempfilestream.writeline(line); } } } // replace original file temporary 1 file.replace("story-temp.txt", "story.txt", null);
Comments
Post a Comment