/* * 2006 - 2018 Ted Spence, http://tedspence.com * License: http://www.apache.org/licenses/LICENSE-2.0 * Home page: https://github.com/tspence/csharp-csv-reader */ using System; using System.Collections.Generic; using ICD.Common.Properties; using ICD.Common.Utils.IO; namespace ICD.Common.Utils.Csv { public sealed class CsvReader : IEnumerable, IDisposable { private readonly CsvReaderSettings m_Settings; private readonly IcdStreamReader m_Instream; #region Public Variables /// /// If the first row in the file is a header row, this will be populated /// public string[] Headers = null; #endregion #region Constructors /// /// Construct a new Csv reader off a streamed source /// /// The stream source /// The Csv settings to use for this reader (Default: Csv) public CsvReader(IcdStreamReader source, [CanBeNull] CsvReaderSettings settings) { m_Instream = source; m_Settings = settings ?? CsvReaderSettings.CSV; // Do we need to parse headers? if (m_Settings.HeaderRowIncluded) { Headers = NextLine(); } else { Headers = m_Settings.AssumedHeaders != null ? m_Settings.AssumedHeaders.ToArray() : null; } } #endregion #region Iterate through a Csv File /// /// Iterate through all lines in this Csv file /// /// An array of all data columns in the line System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return Lines().GetEnumerator(); } /// /// Iterate through all lines in this Csv file /// /// An array of all data columns in the line IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator() { return Lines().GetEnumerator(); } /// /// Iterate through all lines in this Csv file /// /// An array of all data columns in the line public IEnumerable Lines() { return Csv.ParseStream(m_Instream, m_Settings); } /// /// Retrieve the next line from the file. /// DEPRECATED - /// /// One line from the file. public string[] NextLine() { return Csv.ParseMultiLine(m_Instream, m_Settings); } #endregion #region Disposal /// /// Close our resources - specifically, the stream reader /// public void Dispose() { m_Instream.Dispose(); } #endregion } }