c# - Modify FileStream -
i'm working on class allow editing big text files (4gb+). may sound little stupid not understand how can modify text in stream. here code:
public long replace(string text1, string text2) { long replacecount = 0; currentfilestream = file.open(currentfilename, filemode.open, fileaccess.readwrite, fileshare.none); using (bufferedstream bs = new bufferedstream(currentfilestream)) using (streamreader sr = new streamreader(bs)) { string line; while ((line = sr.readline()) != null) { if (line.contains(text1)) { line.replace(text1, text2); // here should save changed line replacecount++; } } } return replacecount; }
you not replacing anywhere in code. should save text , write again file. like,
public long replace(string text1, string text2) { long replacecount = 0; currentfilestream = file.open(currentfilename, filemode.open, fileaccess.readwrite, fileshare.none); stringbuilder sb = new stringbuilder(); using (bufferedstream bs = new bufferedstream(currentfilestream)) using (streamreader sr = new streamreader(bs)) { string line; while ((line = sr.readline()) != null) { string texttoadd = line; if (line.contains(text1)) { texttoadd = line.replace(text1, text2); // here should save changed line replacecount++; } sb.append(texttoadd); } } using (filestream filestream = new filestream(filename , filemode, fileaccess)) { streamwriter streamwriter = new streamwriter(filestream); streamwriter.write(sb.tostring()); streamwriter.close(); filestream.close(); } return replacecount;
}
Comments
Post a Comment