// Taken from JonSkeet's StackOverflow answer here: http://stackoverflow.com/questions/286533/filestream-streamreader-problem-in-c-sharp/286598#286598 using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; namespace Filtration.Common.Utilities { public sealed class LineReader : IEnumerable { /// /// Means of creating a TextReader to read from. /// private readonly Func _dataSource; /// /// Creates a LineReader from a stream source. The delegate is only /// called when the enumerator is fetched. UTF-8 is used to decode /// the stream into text. /// /// Data source [DebuggerStepThrough] public LineReader(Func streamSource) : this(streamSource, Encoding.UTF8) { } /// /// Creates a LineReader from a stream source. The delegate is only /// called when the enumerator is fetched. /// /// Data source /// Encoding to use to decode the stream /// into text [DebuggerStepThrough] public LineReader(Func streamSource, Encoding encoding) : this(() => new StreamReader(streamSource(), encoding)) { } /// /// Creates a LineReader from a filename. The file is only opened /// (or even checked for existence) when the enumerator is fetched. /// UTF8 is used to decode the file into text. /// /// File to read from [DebuggerStepThrough] public LineReader(string filename) : this(filename, Encoding.UTF8) { } /// /// Creates a LineReader from a filename. The file is only opened /// (or even checked for existence) when the enumerator is fetched. /// /// File to read from /// Encoding to use to decode the file /// into text [DebuggerStepThrough] public LineReader(string filename, Encoding encoding) : this(() => new StreamReader(filename, encoding)) { } /// /// Creates a LineReader from a TextReader source. The delegate /// is only called when the enumerator is fetched /// /// Data source [DebuggerStepThrough] public LineReader(Func dataSource) { _dataSource = dataSource; } /// /// Enumerates the data source line by line. /// [DebuggerStepThrough] public IEnumerator GetEnumerator() { using (TextReader reader = _dataSource()) { string line; while ((line = reader.ReadLine()) != null) { yield return line; } } } /// /// Enumerates the data source line by line. /// [DebuggerStepThrough] IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }