How to replace a newline in a large text file in C#

霸气de小男生 提交于 2021-02-11 18:16:14

问题


How can I replace some of the NewLine characters inside a large text (*.csv) file (~ 2 GB) ?

I cannot read the whole file with File.ReadAllText because a get a OutOfMemory Error and I cannot use the StreamReader because it strips away all the NewLine characters.

Here's some sample text:

Row1Field1;Row1Field2;Row1Field3(NewLine)
Row2Field1;Row2Fie(NewLine)  *<--- This newline is by mistake and I want to replace it!*
ld2;Row2Field3(NewLine)
Row3Field1;Row3Field2;Row3Field3(NewLine)

回答1:


You should use StreamReader ( even if you said you cant ) and read the file line by line. When you find a wrong new line, just keep that line in memory and wire up with the one coming next ( maybe more ones if more than one wrong line happens at once ) and write back in the output stream. It does not matter if ReadLine remove the line ending. Just use WriteLine to write in the output stream and you have again the newlines in place.



来源:https://stackoverflow.com/questions/20572086/how-to-replace-a-newline-in-a-large-text-file-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!