Posts

Showing posts from 2015

C# Read File one line at a time

This might seem simple, but often times you find yourself needing to read a file one line at a time no matter what language you do it in. C# makes this very easy with a StreamReader. You simply create the stream reader passing in the file name to the constructor and then call ReadLine on it. See the code below: string line = null; // always use a using with a stream, this ensures it gets disposed of properly using(StreamReader sr = new StreamReader(fileName)) { // we use a while loop until line == null which means end of file while( (line = sr.ReadLine() ) != null ) { // Do something here } }